4

我是 PlayFramework 的新手。

请给我一个示例,如何从我的视图中访问配置参数。我正在使用 PlayFramework 2.5.3

旧方式(@current 已弃用):

@current.configuration.getString("environment.param")

新方法(据我了解,应该注入配置):

我知道如何从控制器访问它。

@Inject() (val messagesApi: MessagesApi, configuration: Configuration)

从我的角度来看,我该如何使用它?

4

3 回答 3

9

遗憾的是,您对此无能为力。DI 引入 Play 时就是这样,关于模板的讨论不多。一种可能的解决方案可能是:

  1. 注入Configuration控制器
  2. 将其发送implicit到您的视图/模板

    class Application @Inject() (implicit val config: Configuration) extends Controller {
    
        def index = Action {
            Ok(views.html.index("foo"))
        }
    }
    

您的模板将如下所示:

@(myParam1: Any)(implicit config: Configuration)
<h2>Some HTML here @myParam1 @config.getString("environment.param")</h2>

我完全意识到这在某种程度上违背了 DI 的目的,但这就是现在的情况。

于 2016-04-30T13:21:20.827 回答
2

看起来 2.6.x 或 twirl 1.2.0 可能会有变化

https://github.com/playframework/twirl/pull/100

https://www.playframework.com/documentation/2.6.x/ScalaTemplates#Template-constructor

于 2016-09-22T10:19:24.190 回答
0

在 java 中,要从 play 2.5 中的 application.conf 读取,您应该在控制器中注入配置,如下所示:

public class HomeController extends Controller {
private Configuration configuration;

@Inject
public HomeController(Configuration configuration) {
    this.configuration = configuration;
}

public Result index() {
    String value = configuration.getString("key");
    System.out.println("value of key is " + key);
    return ok(value);
}

}

因为 Configuration 是一个具体的类,所以不需要在 Module 类中绑定它。

另请参阅此讨论: DI for java in play 2.5

于 2016-05-04T09:50:29.450 回答