Play框架2.1.3函数将使用给定参数呈现scala模板 [英] Play framework 2.1.3 function that will render scala template with given parameters

查看:149
本文介绍了Play框架2.1.3函数将使用给定参数呈现scala模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个方法在我的控制器中以这种方式从它收到的参数调用适当的模板:

I need a method in my controller to call the appropriate template, from the parameters that it received, in this manner:

public static Result renderTemplate(String folder, String template) {
    return ok(
        views.html.<<FOLDER_GOES_HERE>>.<<TEMPLATE_NAME_GOES_HERE>>.render(Users.createForm)
    );
}

如果可能的话?我会用反射来完成它,但由于某些原因我无法列出视图和view.html的字段。

if this possible? I would have done it with reflection, but for some reason I can't list the fields of view and view.html.

有人可以告诉我为什么并解释应该是什么我要做到这一点?

Can someone tell me why and explain what should I do to accomplish this?

谢谢

推荐答案

如果你这样你可能会失去类型安全性和在编译时而不是运行时捕获一些错误的能力。

If you go that way you may loose type safety and the possebility to catch some error on on compile time instead of runtime.

但仍有可能:

final Class<?> clazz = Class.forName("views.html." + folder + "." + template);
//assumed you have a String parameter for your template
java.lang.reflect.Method render = clazz.getDeclaredMethod("render", String.class);
play.api.templates.Html html = (play.api.templates.Html) render.invoke(null, "hi");
return ok(html);

另一种不包括反射开销的方法是在构建时制作模板的索引使用 SBT和源生成器。您可以浏览views文件夹,然后从文件夹/模板名称和调用创建一个地图。

Another way that does no include the overhead of reflection is to make an index of the templates at build time with SBT and source generators. You can walk through the views folder and then create a map from folder/template name and the invokations.

地图位于生成的类中看起来像这样:

The map is in a generated class and looks like this:

map.put("folderx.templatey", views.html.folderx.templatey);//no reflection!

因此,如果模板不存在,至少SBT会在构建时发出警告。

So at least SBT warns you at build time if the template does not exist.

这篇关于Play框架2.1.3函数将使用给定参数呈现scala模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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