简体   繁体   English

Play框架2中的条件视图渲染

[英]Conditional view rendering in play framework 2

I have a very simple question I am not sure how to solve. 我有一个非常简单的问题,我不确定如何解决。 I need render a different template in my Play controller depending on if the view template exists. 我需要根据视图模板是否存在在Play控制器中渲染其他模板。

One of the template is build by an external sbt task and depending on the project state It might not be there as an external dependency based on this I need to render an other template. 模板之一是由外部sbt任务构建的,具体取决于项目状态。基于此,可能不存在外部依赖项,因此我需要呈现其他模板。

Is there an easy way to check if a view template class exists in the Controller ? 有没有一种简单的方法来检查Controller中是否存在视图模板类?

Its a bit ugly since since Play templates are compiled into classes you can try to load the class. 由于Play模板已编译为类,因此您可以尝试加载该类,因此有点难看。

You can try to load the class using Class.forName. 您可以尝试使用Class.forName加载类。 If it exists, then you can use it. 如果存在,则可以使用它。 Since exceptions aren't really recommended for flow control due to performance considerations, you want want to cache the results of this lookup in a singleton somewhere. 由于出于性能方面的考虑,实际上不建议将异常用于流控制,因此您希望将查找结果缓存在某个地方的单例中。

        try {
            Class.forName("views.html.index.class");
        }
        catch(ClassNotFoundException e) {
            //no here
        }

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

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