Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 480
sanity Avatar asked Jan 25 '11 19:01

sanity


1 Answers

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.

like image 174
Codemwnci Avatar answered Sep 23 '22 14:09

Codemwnci