Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

java - Play framework 2.1.3 function that will render scala template with given parameters

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

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?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

But is still possible:

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

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!

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...