开发者

Does Play Framework support "snippets"?

If i want to have a common piece of UI across multiple pages, such as a menu, what is the recommended way to do this?

It would contain both template code and a back-end controller (similar to "snippets" in the Lift开发者_StackOverflow中文版Web framework).

I am aware that there is a menu module for Play, but I'm more interested in how this would be achieved in general.


There are two ways to include common view code into the Play Framework.

You can use the #{include} tag or the #{extends} tag.

The extends tag, as the name suggests, extends from a parent view. The extends tag is used by default in the skeleton code set up by Play when you create a new application. It extends the main.html. You add your code here.

The includes tag, allows you to inject a common piece of view code into your templates at a specified point. This works in much the same was a php include/require, or jsp includes work.

The problem will come when your template code also requires data or logic from the model (via the controller). If this is the case, then you will need to use the @Before or @With notation in your controller to ensure that the common piece of controller code is executed each time. You can add any data to the renderArgs list, so that it is available for use within the view.

A simple example of using renderArgs would be.

@Before
private static void commonData() {
    // do your logic here
    renderArgs.put("menu", menu);
    renderArgs.put("selected", selectedMenuItem);
}

the values you have put into renderArgs (menu and selected in the example) will be available just in the same way as if you passed them into the render method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜