Rendering a portion of a Play framework 2.0 templa

2019-05-19 04:19发布

问题:

I'm trying to call render from a controller for a tag (function) inside a template instead of the template. This way I could use it for partial renderings of a page from ajax calls. Of course I could separate the components of the form in several templates an call render on those but I think it would be cleaner the other way.

What I was trying to do is like the following:

formpage.scala.htm

@()
<html>
...

@content

...
</html>


@**********************************
* Helper generating form *
***********************************@
@content() = {

<h3 class="form-heading">@Messages("employees")</h3>

@form(routes.AppController.save()) {    

@inputText...
...

}

And using ajax render the content function, without having to separate it to a separate file. This way I could render portions of the template without fragmenting it in multiple files.

回答1:

De facto the tag is just smaller template, so you can use tags for both - using in templates and controllers, the simplest sample:

/app/views/tags/mytag.scala.html

This is my tag...

In controller can be rendered as:

public static Result createFromTag(){
    return ok(views.html.tags.mytag.render());
}

In other template you just to insert:

....
And there is my tag rendered
<b>@tags.mytag()</b>

More flexibility

Of course as it's template ergo Scala function as well you can just pass some params to it or even Html body:

/app/views/tags/othertag.scala.html

@(headline: String)(body: Html)

<h3>@headline</h3>
<div class="tagsBody">
    @body
</div>

In controller can be rendered as:

public static Result createFromTag(){

    return ok(
            views.html.tags.othertag.render(
                    "Head from controller",
                    new play.api.templates.Html("This code becomes from <i>controller</b>")
            )
    );
}

(of course you can import these two for shorter code in action import play.api.templates.Html; and import views.html.tags.othertag)

Finally in your template you can use the tag as:

And there is my tag rendered <br/>
@tags.othertag("Head from template"){
    some content for the tag's body from <b>The Template!</b>
}

final.

You'll find tags description in documentation.