Inline variable in the Play framework 2.x Scala template

12,623

Solution 1

First you don't create a variable but a value meaning it's read only.

In your example you have created a value fullName which is accessible inside the curly brackets.

@defining("Farmor") { fullName =>
  <div>Hello @fullName</div>
}

Will print Hello Farmor

To define a value which is accessible globally in your template just embrace everything with your curly brackets.

E.g.

@defining("Value") { formId =>
  @main("Title") {
    @form(routes.Application.addPost, 'id -> formId) {
      @inputText(name = "content", required = true)
      <input type="submit" value="Create">
    }
  }
}

In the example you can use the value formId anywere.

Solution 2

If you don't want to use the @defining syntax you can define a reusable block which will be evaluated every time you use it:

@fullName = @{
  user.firstName + " " + user.lastName
}

<div>Hello @fullName</div>

With this same syntax you can also pass arguments to the block: https://github.com/playframework/Play20/blob/master/samples/scala/computer-database/app/views/list.scala.html

Share:
12,623
user1051870
Author by

user1051870

Updated on June 24, 2022

Comments

  • user1051870
    user1051870 almost 2 years

    How to create an inline variable in the Play framework 2.x Scala template? Path from the Play's guide is not clear to me:

    @defining(user.firstName + " " + user.lastName) { fullName =>
      <div>Hello @fullName</div>
    }
    
  • monzonj
    monzonj over 10 years
    ugly, convoluted! .... So much for all velocity/freemarker efforts to make views really clean and HTML-coder friendly. It seems that now the fashion is make html views a total mess sigh
  • Pedro
    Pedro over 10 years
    I agree! I dislike this syntax very very much.
  • kdkeck
    kdkeck over 10 years
    Except a reusable block will be re-executed every time it is used, while the value of the defining block will only be computed once.