如何在Play 2.0中将多个参数传递到模板中? [英] How is it possible to pass multiple params into a template in Play 2.0?

查看:90
本文介绍了如何在Play 2.0中将多个参数传递到模板中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时将2样东西渲染到我的模板上:

i want to render to my template 2 things at the same time like this:

String one = "one"; 
String two = "two";
return ok(template.render(one,two));

但是Playframework说,这是错误的.那么如何同时渲染2个值呢?我应该将它们保存到列表中吗?但是然后我必须再次将其解压缩到模板中..::

but Playframework says, it is wrong. how is it possible to render 2 values at the same time then? should i save them into a list? but then i have to unpack it again in my template.. :(

请帮助!感谢任何帮助!

please help! appreciate any help!

推荐答案

2.0中的播放模板只是Scala函数,因此您需要在模板的开头(从第1行开始)声明params:

Play templates in 2.0 are just Scala functions, so you need to declare params at the beginning of the template (beginning from line #1):

@(one: String, two: String)

This is first param: @one <br/>
This is second param: @two

检查模板文档以了解详细信息

反之,如果您需要传递大量相同类型的变量,那么Map也是很好的解决方案:

On the other way if you need to pass large quantity of variables of the same type then the Map can be good solution as well:

public static Result index() {

    Map<String, String> labels = new HashMap<String, String>();

    labels.put("first", "First label");
    labels.put("second", "Second label");
    // etc etc
    labels.put("hundredth", "Label no. 100");

    return ok(template.render(labels));
}

template.scala.html

@(labels: Map[String, String])

@labels.get("first") <br/>
@labels.get("second") <br/>
.....
@labels.get("hundredth")

查看模型

最后,为了使事情更加类型安全,您可以创建自己的view models,例如(示例):

View model

Finally to make things even more typesafe you can create your own view models like (sample):

package models.view;

import java.util.Date;

public class MyViewModel {

    public String pageTitle = "";
    public Date currentDate = new Date();
    public Integer counter = 0;
    // etc...

}

控制器:

public static Result myActionUsingModel() {
    MyViewModel data = new MyViewModel();
    data.pageTitle = "Ellou' World!";
    data.counter = 123;

    return ok(myViewUsingModel.render(data));
}

视图:

@(data: models.view.MyViewModel)

<h1>@data.pageTitle</h1>

<div>Now is: @data.currentDate</div>
<div>The counter value is: @data.counter</div>

这篇关于如何在Play 2.0中将多个参数传递到模板中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆