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

查看:19
本文介绍了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 设置的框架代码中使用 extends 标签.它扩展了 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 包含/要求或 jsp 包含工作大致相同.

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天全站免登陆