Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid passing parameters everywhere in play2?
    primarykey
    data
    text
    <p>In play1, I usually get all data in actions, use them directly in views. Since we don't need to explicitly declare parameters in view, this is very easy.</p> <p>But in play2, I found we have to declare all the parameters(including <code>request</code>) in the head of views, it will be very boring to get all data in actions and pass them into views.</p> <p>For example, if I need to display menus which are loaded from database in the front page, I have to define it in <code>main.scala.html</code>:</p> <pre><code>@(title: String, menus: Seq[Menu])(content: Html) &lt;html&gt;&lt;head&gt;&lt;title&gt;@title&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;div&gt; @for(menu&lt;-menus) { &lt;a href="#"&gt;@menu.name&lt;/a&gt; } &lt;/div&gt; @content &lt;/body&gt;&lt;/html&gt; </code></pre> <p>Then I have to declare it in every sub page:</p> <pre><code>@(menus: Seq[Menu]) @main("SubPage", menus) { ... } </code></pre> <p>Then I have to get the menus and pass it to view in every action:</p> <pre><code>def index = Action { val menus = Menu.findAll() Ok(views.html.index(menus)) } def index2 = Action { val menus = Menu.findAll() Ok(views.html.index2(menus)) } def index3 = Action { val menus = Menu.findAll() Ok(views.html.index(menus3)) } </code></pre> <p>For now it's only one parameter in <code>main.scala.html</code>, what if there are many?</p> <p>So at last, I decided to all <code>Menu.findAll()</code> directly in view:</p> <pre><code>@(title: String)(content: Html) &lt;html&gt;&lt;head&gt;&lt;title&gt;@title&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;div&gt; @for(menu&lt;-Menu.findAll()) { &lt;a href="#"&gt;@menu.name&lt;/a&gt; } &lt;/div&gt; @content &lt;/body&gt;&lt;/html&gt; </code></pre> <p>I don't know if it is good or recommended, is there any better solution for this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload