How is it possible to pass multiple params into a template in Play 2.0?

后端 未结 1 1828
夕颜
夕颜 2021-01-04 14:28

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));


        
相关标签:
1条回答
  • 2021-01-04 14:45

    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
    

    Check the templates docs for details

    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 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...
    
    }
    

    controller:

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

    view:

    @(data: models.view.MyViewModel)
    
    <h1>@data.pageTitle</h1>
    
    <div>Now is: @data.currentDate</div>
    <div>The counter value is: @data.counter</div>
    
    0 讨论(0)
提交回复
热议问题