Skip to content

Using with Play

Maxim Karpov edited this page Apr 20, 2016 · 1 revision

To use Scalingua with Play web application (for plain Scala application use this guide), you need to include Scalingua both as library dependency and SBT plugin, and to adjust some SBT defaults to match Play project structure. To do this, you should add following lines to build configuration:


project/plugins.sbt:

addSbtPlugin("ru.makkarpov" % "scalingua-sbt" % VERSION)

build.sbt:

enablePlugins(Scalingua)

libraryDependencies += "ru.makkarpov" %% "scalingua-play" % VERSION

// By default it would be `app/locales`, so redirect it to `conf`.
sourceDirectories in (Compile, compileLocales) := Seq(file("conf/locales"))

// To avoid importing `I18n` every time in templates
TwirlKeys.templateImports += "ru.makkarpov.scalingua.play.I18n._"

The translation functions are looking much the same as plain Scala ones, with the following exceptions:

  • You should import ru.makkarpov.scalingua.play.I18n._ instead of just ru.makkarpov.scalingua.I18n._
  • You don't need to provide LanguageId if you have implicit RequestHeader — language ID will be extracted from Accept-Language header automagically.
  • All plain string functions have their HTML equivalents, e.g. t"qwe" -> h"qwe". HTML functions allows to safely insert interpolation variables and don't worry about XSS:
val str = "<script>XSS!</script>"
h"<strong>$str</strong>" // -> <strong>&lt;script&gt;XSS!&lt;/script&gt;</strong>

Messages and global state

Since global state is discouraged in Play framework, Messages can be used with @Inject annotation. To enable it, you should add following lines to application.conf:

scalingua {
  package = "locales"
}

play.modules.enabled += "ru.makkarpov.scalingua.play.ScalinguaModule"

After that you can use them just like any other injectable component:


controllers/Application.scala:

class Application @Inject()(implicit msgs: Messages) extends Controller {
  // ...
}

Clone this wiki locally