简体   繁体   English

在Application.java中按名称返回结果视图

[英]Return result view by name in Application.java

In a Play 2.2! 在Play 2.2中! web project I'm pursuing, I'd like to return views by name in Application.java 我追求的Web项目,我想按名称返回Application.java中的视图

I've added the following in the routes config : 我在路由配置中添加了以下内容:

GET     /:page                      controllers.Application.show(page: String)

And i'd like Application.java to return the correct view only using it's name (the String page). 而且我希望Application.java仅使用其名称(“字符串”页面)返回正确的视图。

At the moment I have : 目前,我有:

public static Result show(String page) {
    switch(page){
        case "home":
            return ok(home.render());
        case "register":
            return ok(register.render());
    }
    return ok(home.render());
}

I'd like to avoid the switch statement here, and have show(String page) programatically find the view that matches the String page given in argument and return it (or home page if no match has been found). 我想避免在这里使用switch语句,并让show(String page)以编程方式找到与参数中给定的String页面匹配的视图,然后将其返回(如果找不到匹配项,则返回主页)。

EDIT : I've read some stuff about reflexion but I don't really know what that is or how to use it :/ 编辑:我已经读过一些有关反射的东西,但我真的不知道那是什么或如何使用它:/

Thanks for your insight :) 感谢您的见解:)

Remember that Play's view is a Scala function - which takes parameters, for ensuring typesafety , dynamic content etc, etc. In this scenario you shouldn't use :path argument but make usage of different routes to different actions like: 请记住,Play的视图是一个Scala函数-它带有参数,以确保类型安全动态内容等。在这种情况下,您不应使用:path参数,而应将不同的路由用于不同的动作,例如:

GET     /home           controllers.Application.home
GET     /register       controllers.Application.register

Actions: 动作:

public static Result home() {
    return ok(home.render());
}

public static Result register() {
    return ok(register.render());
}

Crypto-advertisment: Use Intellij - create templates for actions and routes and you will be doing it within milliseconds ;) 加密广告:使用Intellij-为操作和路由创建模板,您将在几毫秒内完成操作;)

On the other hand if you have a large set of HTML files you can render them as... files instead of Play views like ( pseudo code, debug it yourself! ) 另一方面,如果您有大量的HTML文件,则可以将它们呈现为...文件,而不是Play视图,例如( 伪代码,请自行调试!

public static Result show(String page) {

    File htmlFile = new File(page+".html");
    if (!htmlFile.exists()) htmlFile = new File("home.html");

    return ok(htmlFile).as("text/html");
}

I will only add that is absolutely NOT Play's way for working with templates ;) 我只会补充一点,这绝对不是 Play使用模板的方式;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM