0

I have a Play! framework with two actions which contain redundant code. So I factored this code into a private static method, but It doesn't work anymore then.

  public static void show(long itemId, String listId) {
    render(getItem(itemId, listId));
  }

  private static Item getItem(long itemId, String listId) {
    // otherwise duplicate code ...
    return item;
  }

If I inline the code contained in getItem into the show action everything is fine:

  // this works
  public static void show(long itemId, String listId) {
    Item item = // duplicate code ...
    render(item);
  }

Why can I not call other static methods within a Play! controller?

Solution

Thanks to 'Codemwnci' I've implemented the following solution:

  public static void show(long itemId, String listId) {
    renderArgs.put("item", getItem(itemId, listId));
    render();
  }

I prefer renderArgs because it makes the intention more clear than a local variable.

deamon
  • 89,107
  • 111
  • 320
  • 448
  • Have in mind that if you make the helper-method public a redirect is happened. See http://stackoverflow.com/questions/3899670/how-can-i-influence-the-redirect-behavior-in-a-play-controller. This isn't your problem now, but could be the next, where some magic happens. – niels Nov 08 '11 at 07:28

1 Answers1

4

When you pass a local variable into the render method, the name of the local variable is used when passed through to the Groovy view. In your example, you are not passing a local variable, therefore Play does not know what name to give the item you have specified.

You have a couple of options. You can do either

  1. Set the return from getItem to a local variable (item), and pass item into the view
  2. Set the return from getItem into the renderArgs map, and specify your own name.

Option 1 is probably the most sensible.

Codemwnci
  • 54,176
  • 10
  • 96
  • 129
  • 1
    it is one of the things that is intended to be addressed in Play2.0, but this convention does significantly reduce code by not having to map variables from controllers into the view – Codemwnci Nov 07 '11 at 22:22