简体   繁体   English

在视图中使用 application.conf 属性 Play Scala

[英]Using application.conf properties in views Play Scala

I have a link to open a website in one of the views in my application and I need for that website to be dependant on a site set in application.conf.我有一个链接可以在我的应用程序中的一个视图中打开一个网站,我需要该网站依赖于 application.conf 中设置的网站。

View now:现在查看:

class="nav-link" href="https://my.website.com" target="_blank"> class="nav-link" href="https://my.website.com" target="_blank">

This doesn't work:这不起作用:

class="nav-link" href=current.configuration.getString("client.server.url") target="_blank"> class="nav-link" href=current.configuration.getString("client.server.url") target="_blank">

application.conf:应用程序.conf:

client.server.url = " https://my.website.com " client.server.url = " https://my.website.com "

Any help would be appreciated.任何帮助,将不胜感激。

In order to use Configuration inside a Play Template you need to inyect it into the Controller and then give it to the view though its constructor. 为了在“播放模板”中使用“配置”,您需要将其注入到Controller中,然后通过其构造函数将其提供给视图。

@Singleton
class FooController @Inject()(config:Configuration, cc: ControllerComponents) extends AbstractController(cc) {

  def bar = Action {
    Ok(views.html.baz(config))
  }

}

then your view baz.scala.html 然后您的视图baz.scala.html

@(config:play.api.Configuration)

<a class="nav-link" href="@config.getString("client.server.url")" target="_blank">LINK</a>

I use eg @{play.Play.application.configuration.getString("play.http.context")} but it might be deprecated in version 2.6. 我使用例如@{play.Play.application.configuration.getString("play.http.context")}但在2.6版中可能已弃用。 Just exchange play.http.context with your config parameter. 只需与您的config参数交换play.http.context

There are multiple ways to access configurations in Play using Scala有多种方法可以使用 Scala 访问 Play 中的配置

The following works on Play 2.7.x以下适用于 Play 2.7.x

Option 1: With DI选项 1:使用 DI

import play.api.Configuration
.... other imports ...

class MyActor @Inject()(config: Configuration) extends Actor  {
 println(config.get[String]("akka_actor_custom_dispatcher"))
 println(config.get[String]("akka_actor_custom_dispatcher")) // w/o optional
 println(config.getOptional[Int]("value_1").getOrElse(2))    // with optional 
 .....
 }

Option 2: w/o DI选项 2:无 DI

import play.api.Configuration
.... other imports ...

class MyActor() extends Actor {
 val config = new Configuration(ConfigFactory.load("application.conf"))
 println(config.get[String]("akka_actor_custom_dispatcher"))
 println(config.get[String]("akka_actor_custom_dispatcher")) // w/o optional
 println(config.getOptional[Int]("value_1").getOrElse(2))    // with optional 
 .....
 }

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

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