Play Framework是否支持“代码段"? [英] Does Play Framework support "snippets"?

查看:73
本文介绍了Play Framework是否支持“代码段"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在多个页面(例如菜单)上有一个通用的UI,推荐的这样做方法是什么?

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?

它将同时包含模板代码和后端控制器(类似于LiftWeb框架中的代码段").

It would contain both template code and a back-end controller (similar to "snippets" in the LiftWeb framework).

我知道有一个Play菜单模块,但我对总体上如何实现更感兴趣.

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

推荐答案

有两种方法可以将通用视图代码包含在Play框架中.

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

您可以使用#{include}标记或#{extends}标记.

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

顾名思义,extends标签是从父视图扩展而来的.当您创建新的应用程序时,默认情况下,扩展标记用于Play设置的框架代码中.它扩展了main.html.您可以在此处添加代码.

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.

includes标记,使您可以在指定点将通用的视图代码片段插入模板中.这项工作与php include/require或jsp includes的工作原理几乎相同.

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.

当您的模板代码还需要模型中的数据或逻辑(通过控制器)时,就会出现问题.如果是这种情况,那么您将需要在控制器中使用@Before或@With表示法,以确保每次都执行通用的控制器代码.您可以将任何数据添加到renderArgs列表中,以便可以在视图中使用.

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.

使用renderArgs的简单示例是.

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

您放入renderArgs中的值(在示例中为菜单和选定值)将可用,就像将它们传递到render方法中一样.

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.

这篇关于Play Framework是否支持“代码段"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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