本文整理汇总了Scala中play.api.i18n.Lang类的典型用法代码示例。如果您正苦于以下问题:Scala Lang类的具体用法?Scala Lang怎么用?Scala Lang使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Lang类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: IfTag
//设置package包名称以及导入依赖的类
package helpers
import models._
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, Days}
import org.joda.time.Minutes
import org.joda.time.Hours
import play.api.Play
import play.api.Play.current
import play.api.i18n.Lang
import play.twirl.api.Html
import utils.DateUtils
import utils.m
import play.api.mvc.WrappedRequest
class IfTag(condition: Boolean, content: => Html) extends scala.xml.NodeSeq {
def theSeq = Nil // just ignore, required by NodeSeq
override def toString = if (condition) content.toString else ""
def orElse(failed: => Html) = if (condition) content else failed
}
object CustomTag {
def date2delay(d: DateTime)(implicit request: WrappedRequest[_]): String = {
val d_minus_seven_days = DateUtils.now.minusDays(7)
val d_minus_one_days = DateUtils.now.minusDays(1)
val d_minus_one_hours = DateUtils.now.minusHours(1)
val now = DateUtils.now
if (d.isAfterNow) { "" }
else if (d.isAfter(d_minus_one_hours)) {
val minutes_delta = Minutes.minutesBetween(d, now)
m("general.date.delay.minutes", Math.abs(minutes_delta.getMinutes))
} else if (d.isAfter(d_minus_one_days)) {
val hours_delta = Hours.hoursBetween(d, now)
m("general.date.delay.hours", Math.abs(hours_delta.getHours))
} else if (d.isAfter(d_minus_seven_days.toInstant)) {
val day_delta = Days.daysBetween(d, now)
m("general.date.delay.days", Math.abs(day_delta.getDays))
} else {
m("general.date.delay.on", date_format(d, Some("MMM")), d.getDayOfMonth)
}
}
def date_format(date: DateTime, format: Option[String] = None)(implicit lang: Lang): String = {
val pattern = format
.orElse(Play.configuration.getString(s"date.i18n.date.format.${lang.language}"))
.getOrElse("dd/MM/yyyy")
val locale = lang.toLocale
val formatter = DateTimeFormat.forPattern(pattern).withLocale(locale)
formatter.print(date)
}
}
示例2: toResult
//设置package包名称以及导入依赖的类
package api
import ApiResponse._
import ApiError._
import models.ApiLog
import play.api.mvc.Results._
import play.api.mvc.{ Result, RequestHeader }
import play.api.libs.json._
import play.api.libs.json.Json._
import play.api.i18n.Lang
def toResult[R <: RequestHeader](implicit request: R, lang: Lang): Result = {
val envelope = request.getQueryString("envelope") == Some("true")
toResult(envelope)
}
def toResult(envelope: Boolean = false)(implicit lang: Lang): Result = {
val js = if (envelope) envelopedJson else json
(status match {
case STATUS_CREATED => if (js == JsNull) Created else Created(js)
case STATUS_ACCEPTED => if (js == JsNull) Accepted else Accepted(js)
case STATUS_NOCONTENT => NoContent
case s if s < 300 => if (js == JsNull) Ok else Ok(js)
case STATUS_BADREQUEST => BadRequest(js)
case STATUS_UNAUTHORIZED => Unauthorized(js)
case STATUS_FORBIDDEN => Forbidden(js)
case STATUS_NOTFOUND => NotFound(js)
case s if s > 400 && s < 500 => BadRequest(js)
case _ => InternalServerError(js)
}).withHeaders((headers ++ Api.basicHeaders): _*)
}
}
示例3: SelectionItem
//设置package包名称以及导入依赖的类
package controllers
import play.api.i18n.Messages
import play.api.i18n.Lang
case class SelectionItem(text: String,
icon: Option[String] = None,
localized: Boolean = true) {
def localizedText(implicit lang: Lang, messages: Messages) = {
if (localized) {
Messages(text)
} else {
text
}
}
}
示例4: Application
//设置package包名称以及导入依赖的类
package controllers.web
import models.web._
import play.api._
import play.api.mvc._
import play.api.i18n.{ I18nSupport, MessagesApi, Messages, Lang }
import javax.inject.Inject
class Application @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {
def index = Action { implicit request =>
Ok(views.html.web.index())
}
def selectLang(lang: String) = Action { implicit request =>
Logger.logger.debug("Change user lang to : " + lang)
request.headers.get(REFERER).map { referer =>
Redirect(referer).withLang(Lang(lang))
}.getOrElse {
Redirect(routes.ApplicationController.index).withLang(Lang(lang))
}
}
}
示例5: Application
//设置package包名称以及导入依赖的类
package controllers.admin
import models.admin._
import play.api._
import play.api.mvc._
import play.api.i18n.{ I18nSupport, MessagesApi, Messages, Lang }
import javax.inject.Inject
class Application @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {
def index = Action { implicit request =>
val computers = ComputerAdmin.list
Ok(views.html.admin.index(Messages("admin.subtitle"), computers))
}
def selectLang(lang: String) = Action { implicit request =>
Logger.logger.debug("Change user lang to : " + lang)
request.headers.get(REFERER).map { referer =>
Redirect(referer).withLang(Lang(lang))
}.getOrElse {
Redirect(routes.Application.index).withLang(Lang(lang))
}
}
}
示例6: password
//设置package包名称以及导入依赖的类
package views.html.htmlForm
import play.api.data.Field
import play.api.i18n.Lang
import play.twirl.api.Html
import views.html.helper.FieldConstructor
object password {
def apply(field: Field, label: String, args: (Symbol, Any)*)
(implicit handler: FieldConstructor, lang: Lang): Html =
Html {
val label2 = if (label.endsWith("*")) s"${ label.substring(0, label.length-1) }<sup>*</sup>" else label
s"""<dl ${ if (field.errors.nonEmpty) "class='error'" else "" } id="${ field.id }_label">
| <dt><label for="${ field.id }">$label2</label></dt>
| <dd><input type="password" id="${ field.id }" name="${ field.id }" value="${ field.value }">
| ${ if (field.errors.nonEmpty) field.errors else "" }</dd>
|</dl>
|""".stripMargin
}
}
示例7: checkbox
//设置package包名称以及导入依赖的类
package views.html.htmlForm.bootstrap3
import play.api.data.Field
import play.api.i18n.{Lang, Messages}
import play.api.templates.PlayMagic.toHtmlArgs
import play.twirl.api.Html
import views.html.helper.{FieldConstructor, input => playInput}
object checkbox {
def apply(field: Field, args: (Symbol, Any)*)
(implicit handler: FieldConstructor, lang: Lang, messages: Messages): Html = {
val boxValue = args.toMap.getOrElse('value, "true")
playInput(field, args:_*) { (id, name, value, htmlArgs) =>
Html(s"""<label class="checkbox">
| <input type="checkbox" name="$name" value="$boxValue"
| ${ if (value.contains(boxValue)) "checked" else "" } ${ toHtmlArgs(htmlArgs.filterKeys(_ != 'value)) } />
| ${ args.toMap.getOrElse('_text, "") }
|</label>
|""".stripMargin)
}
}
}
示例8: LocalizationController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.mohiva.play.silhouette.api.Silhouette
import play.api.i18n.{ I18nSupport, MessagesApi, Lang }
import play.api.mvc.Controller
import utils.auth.DefaultEnv
class LocalizationController @Inject() (
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv])
extends Controller with I18nSupport {
def langDE = silhouette.UserAwareAction { implicit request =>
val referrer = request.headers.get(REFERER).getOrElse("/")
Redirect(referrer).withLang(Lang("de"))
}
def langEN = silhouette.UserAwareAction { implicit request =>
val referrer = request.headers.get(REFERER).getOrElse("/")
Redirect(referrer).withLang(Lang("en"))
}
}
示例9: Import
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import services.VocabularyService
import models.Vocabulary
import play.api.mvc._
import play.api.i18n.Lang
class Import @Inject() (vocabulary: VocabularyService) extends Controller {
def importWord(
sourceLanguage: Lang,
word: String,
targetLanguage: Lang,
translation: String) = Action { request =>
val added = vocabulary.addVocabulary(
Vocabulary(sourceLanguage, targetLanguage, word, translation)
)
if (added) Ok else Conflict
}
}
示例10: Quizz
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import services.VocabularyService
import play.api.mvc._
import play.api.i18n.Lang
class Quizz @Inject() (vocabulary: VocabularyService) extends Controller {
def quizz(sourceLanguage: Lang, targetLanguage: Lang) = Action { request =>
vocabulary.findRandomVocabulary(sourceLanguage, targetLanguage) match {
case Some(_) => Ok
case None => NotFound
}
}
def check(sourceLanguage: Lang, word: String, targetLanguage: Lang, translation: String) = Action { request =>
vocabulary.verify(sourceLanguage, word, targetLanguage, translation) match {
case true => Ok
case false => NotAcceptable
}
}
}
示例11: VocabularyService
//设置package包名称以及导入依赖的类
package services
import models.Vocabulary
import javax.inject.Singleton
import scala.util.Random
import play.api.i18n.Lang
@Singleton
class VocabularyService {
private var allVocabulary = List(
Vocabulary(Lang("en"), Lang("es"), "hello", "hola"),
Vocabulary(Lang("en"), Lang("es"), "play", "jugar")
)
def addVocabulary(v: Vocabulary): Boolean = {
if (!allVocabulary.contains(v)) {
allVocabulary = v :: allVocabulary
true
} else {
false
}
}
def findRandomVocabulary(sourceLanguage: Lang, targetLanguage: Lang): Option[Vocabulary] = {
Random.shuffle(allVocabulary.filter { v =>
v.sourceLanguage == sourceLanguage &&
v.targetLanguage == targetLanguage
}).headOption
}
def verify(sourceLanguage: Lang, word: String, targetLanguage: Lang, translation: String): Boolean = {
allVocabulary.contains(Vocabulary(sourceLanguage, targetLanguage, word, translation))
}
}
示例12: JsDump
//设置package包名称以及导入依赖的类
package lila.i18n
import java.io._
import scala.concurrent.Future
import play.api.i18n.Lang
import play.api.libs.json.{ JsString, JsObject }
private[i18n] final class JsDump(
path: String,
pool: I18nPool,
keys: I18nKeys
) {
def keysToObject(keys: Seq[I18nKey], lang: Lang) = JsObject {
keys.map { k =>
k.key -> JsString(k.to(lang)())
}
}
def keysToMessageObject(keys: Seq[I18nKey], lang: Lang) = JsObject {
keys.map { k =>
k.en() -> JsString(k.to(lang)())
}
}
def apply: Funit = Future {
pathFile.mkdir
writeRefs
writeFullJson
} void
private val pathFile = new File(path)
private def dumpFromKey(messages: List[I18nKey], lang: Lang): String =
messages.map { key =>
""""%s":"%s"""".format(key.key, escape(key.to(lang)()))
}.mkString("{", ",", "}")
private def writeRefs {
val code = pool.names.toList.sortBy(_._1).map {
case (code, name) => s"""["$code","$name"]"""
}.mkString("[", ",", "]")
val file = new File("%s/refs.json".format(pathFile.getCanonicalPath))
val out = new PrintWriter(file)
try { out.print(code) }
finally { out.close }
}
private def writeFullJson {
pool.langs foreach { lang =>
val code = dumpFromKey(keys.keys, lang)
val file = new File("%s/%s.all.json".format(pathFile.getCanonicalPath, lang.language))
val out = new PrintWriter(file)
try { out.print(code) }
finally { out.close }
}
}
private def escape(text: String) = text.replace(""""""", """\"""")
}
示例13: FileFix
//设置package包名称以及导入依赖的类
package lila.i18n
import scala.concurrent.Future
import play.api.i18n.Lang
private[i18n] final class FileFix(
pool: I18nPool,
path: String,
keys: I18nKeys,
messages: Messages
) {
val apply: Funit =
Future.traverse(pool.nonDefaultLangs.toList)(fix).void
private def fix(lang: Lang): Funit =
write(lang, sanitize((messages get lang.language) | Map.empty))
private def sanitize(messages: Map[String, String]) =
keys.keys map { key =>
messages get key.key filter { message =>
hasVariable(key.to(pool.default)()).fold(hasVariable(message), true)
} map (key.key -> _)
} flatten
private def hasVariable(message: String) = message contains "%s"
private def write(lang: Lang, messages: List[(String, String)]) = {
val file = "%s/messages.%s".format(path, lang.language)
printToFile(file) { writer =>
messages foreach {
case (name, trans) => writer.println(name + "=" + trans)
}
}
}
}
示例14: Translator
//设置package包名称以及导入依赖的类
package lila.i18n
import play.api.i18n.Lang
import play.api.mvc.RequestHeader
import play.twirl.api.Html
private[i18n] final class Translator(messages: Messages, pool: I18nPool) {
private val defaultMessages = messages.get("default") err "No default messages"
def html(key: String, args: List[Any])(implicit req: RequestHeader): Html =
Html(str(key, args)(req))
def str(key: String, args: List[Any])(implicit req: RequestHeader): String =
translate(key, args)(pool lang req) getOrElse key
def transTo(key: String, args: Seq[Any])(lang: Lang): String =
translate(key, args)(lang) getOrElse key
def rawTranslation(lang: Lang)(key: String): Option[String] =
messages get lang.language flatMap (_ get key)
private def defaultTranslation(key: String, args: Seq[Any]): Option[String] =
defaultMessages get key flatMap { pattern =>
formatTranslation(key, pattern, args)
}
private def translate(key: String, args: Seq[Any])(lang: Lang): Option[String] =
if (lang.language == pool.default.language) defaultTranslation(key, args)
else messages get lang.language flatMap (_ get key) flatMap { pattern =>
formatTranslation(key, pattern, args)
} orElse defaultTranslation(key, args)
private def formatTranslation(key: String, pattern: String, args: Seq[Any]) = try {
Some(if (args.isEmpty) pattern else pattern.format(args: _*))
}
catch {
case e: Exception =>
logger.warn(s"Failed to translate $key -> $pattern ($args)", e)
None
}
}
示例15: TransInfo
//设置package包名称以及导入依赖的类
package lila.i18n
import play.api.i18n.Lang
case class TransInfo(
lang: Lang,
name: String,
contributors: List[String],
nbTranslated: Int,
nbMissing: Int
) {
def code = lang.language
def codeAndName = code + " - " + name
def nbMessages = nbTranslated + nbMissing
def percent = nbTranslated * 100 / nbMessages
def complete = percent == 100
def nonComplete = !complete
}
private[i18n] case class TransInfos(all: List[TransInfo]) {
lazy val byCode = all map { info =>
info.code -> info
} toMap
def get(code: String): Option[TransInfo] = byCode get code
def get(lang: Lang): Option[TransInfo] = get(lang.language)
}
private[i18n] object TransInfos {
val defaultCode = "en"
def apply(messages: Messages, keys: I18nKeys): TransInfos = TransInfos {
val nbMessages = keys.count
LangList.sortedList.filter(_._1 != defaultCode) map {
case (code, name) => TransInfo(
lang = Lang(code),
name = name,
contributors = Contributors(code),
nbTranslated = messages.get(code) ?? (_.size),
nbMissing = nbMessages - (messages.get(code) ?? (_.size))
)
}
}
}