1

I have not been able to solve this specific case from the examples provided in the documentation.

I create a Result:

    Customer customer = new Customer("James");
    Order[] orders = new Order[2];
    orders[0] = new Order("Apple");
    orders[1] = new Order("Orange");
    Content html = views.html.template.render(customer, orders);
    return ok(html);

And my template is:

@(customer: Customer, orders: Array[Order])

<h1>Welcome @customer.name!</h1>

<ul> 
    @for(order <- orders) {
      <li>@order.name</li>
    }
</ul>

Now I want to add a Boolean variable in the template, then iterate through the orders, and if Apple appears in the orders, I want to set the created variable to true.

Basically I need a var that has scope throughout the whole template.

Thank you.

Added some pseudocode.

@(customer: Customer, orders: Array[Order])

<h1>Welcome @customer.name!</h1>

**** var containsApple = false;

<ul> 
    @for(order <- orders) {
      <li>@order.name</li>

      **** if order.name == "apple"
      ****   containsApple = true;

    }
</ul>
1
  • See: stackoverflow.com/a/11289347/136363 Perhaps if you told us what you're trying to achieve (i.e. what you need the boolean for), we could help find an alternative route to your goal? Commented Dec 30, 2013 at 23:20

2 Answers 2

3

I would definitely move this logic into controller to avoid spaghetti code. Otherwise you can declare a new variable like this: Declare variable in a Play2 scala template

Sign up to request clarification or add additional context in comments.

Comments

2

I can't speak for play templates, but in regular Scala this would be:

val containsApple = orders.exists(_.name == "apple")

No need for a var or any other form of scary mutability.

2 Comments

It looks like the controller method is actually written in Java.
Sure... But the controller ain't

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.