本文整理汇总了Scala中play.twirl.api.Html类的典型用法代码示例。如果您正苦于以下问题:Scala Html类的具体用法?Scala Html怎么用?Scala Html使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Html类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: folder
//设置package包名称以及导入依赖的类
package helpers
import play.api.templates.PlayMagic
import play.twirl.api.Html
private[helpers] sealed trait asset {
protected val ext = "" //." + folder
protected def folder: String
protected def toArgs(args: (Symbol, Any)*) = PlayMagic.toHtmlArgs(args.toMap).body
protected def opt(t: String, r: => String) = if (t == null || t.trim == "") "" else r
def url(resource: String, absolute: Boolean = false) = controllers.routes.Assets.versioned(folder + "/" + resource + ext).url
}
object css extends asset {
protected def folder = "css"
def apply(resource: String, media: String = "") = {
val m = opt(media, s""" media="$media" """)
Html(s"""<link href="${url(resource)}"$m rel="stylesheet">""")
}
}
object img extends asset {
override protected val ext = ""
protected def folder = "images"
def apply(resource: String, args: (Symbol, Any)*): Html = apply(resource, "", args: _*)
def apply(resource: String, alt: String, args: (Symbol, Any)*) = {
val a = opt(alt, s""" alt="$alt" """)
val t = toArgs(args: _*)
val r = opt(t, " " + t)
Html(s"""<img src="${url(resource)}"$a$r>""")
}
}
object js extends asset {
protected def folder = "js"
def apply(resource: String) = Html(s"""<script src="${url(resource)}"></script>""")
}
示例2: 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)
}
}
示例3: FrontendGlobal
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.trustregistration
import java.io.File
import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import play.api.Mode._
import play.api.mvc.Request
import play.api.{Application, Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.play.audit.filters.FrontendAuditFilter
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.frontend.bootstrap.DefaultFrontendGlobal
import uk.gov.hmrc.play.http.logging.filters.FrontendLoggingFilter
object FrontendGlobal
extends DefaultFrontendGlobal {
override val auditConnector = FrontendAuditConnector
override val loggingFilter = LoggingFilter
override val frontendAuditFilter = AuditFilter
override def onStart(app: Application) {
super.onStart(app)
ApplicationCrypto.verifyConfiguration()
}
override def onLoadConfig(config: Configuration, path: File, classloader: ClassLoader, mode: Mode): Configuration = {
super.onLoadConfig(config, path, classloader, mode)
}
override def standardErrorTemplate(pageTitle: String, heading: String, message: String)(implicit rh: Request[_]): Html =
uk.gov.hmrc.trustregistration.views.html.error_template(pageTitle, heading, message)
override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")
}
object ControllerConfiguration extends ControllerConfig {
lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}
object LoggingFilter extends FrontendLoggingFilter {
override def controllerNeedsLogging(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsLogging
}
object AuditFilter extends FrontendAuditFilter with RunMode with AppName {
override lazy val maskedFormFields = Seq("password")
override lazy val applicationPort = None
override lazy val auditConnector = FrontendAuditConnector
override def controllerNeedsAuditing(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsAuditing
}
示例4: Utils
//设置package包名称以及导入依赖的类
package controllers
import models.mv.ConceptoFinal
import play.api.libs.json.Json
import play.twirl.api.Html
import scala.io.Source
import scala.util.{Failure, Try}
object Utils {
def cargarJson(ruta: String): Try[String] = Try {
Source.fromInputStream(getClass.getResourceAsStream(ruta)).mkString
} recoverWith {
case f => Failure(new Exception("NOT_FOUND"))
}
def parsearJsonAConcepto(negocio: String): Try[ConceptoFinal] = Try {
Json.parse(negocio).as[ConceptoFinal]
} recoverWith {
case f => Failure(new Exception("MALFORMED_JSON"))
}
def construirConceptoFinal(rutaNegocio: String) = for {
negocio <- cargarJson(rutaNegocio)
conceptoFinal <- parsearJsonAConcepto(negocio)
} yield conceptoFinal
def agregarAlIndex(content: Html) = views.html.mv.indexAngular(content)
def ordenarConceptoFinalPorPosicion(lista: List[ConceptoFinal]) = {
val (complejos, noComplejos) = lista.partition(_.concepto.tipo == "complejo")
complejos.sortBy(_.concepto.posicion ) ++ noComplejos.sortBy(_.concepto.posicion)
}
def generarId(idPadre: String, idConcepto: String): (String, String) = {
val id= s"$idPadre-$idConcepto"
(id.replaceAll("-", "."), id)
}
}
示例5: NavigationController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import play.api.data._
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.ws.WSClient
import play.api.mvc.{Action, Controller}
import play.twirl.api.Html
class NavigationController @Inject() (ws: WSClient) (val messagesApi: MessagesApi) extends Controller with I18nSupport{
def navigate() = Action.async
{
implicit request =>
val xml : UserXML = xmlForm.bindFromRequest().get
val code = scala.xml.XML.loadString(xml.xml)
val pageId = (code \ "state" \ "page-id").text
val selections = code \ "selection"
val selectionNumbers = selections.map(i => (i \ "@page-id").text)
val texts = code \ "text"
val textNumbers = texts.map(i => (i \ "@page-id").text)
val paragraphs = code \ "paragraph"
val paragraphNumbers = paragraphs.map(i => (i \ "@page-id").text)
implicit val context = play.api.libs.concurrent.Execution.Implicits.defaultContext
if (selectionNumbers.contains(pageId)){
ws.url("http://" + request.host + "/selection/").post(Map("xml" -> Seq(xml.xml))).map { response =>
Ok(Html(response.body))
}
}else if(textNumbers.contains(pageId)) {
ws.url("http://" + request.host + "/text/").post(Map("xml" -> Seq(xml.xml))).map { response =>
Ok(response.body)
}
}else if(paragraphNumbers.contains(pageId)) {
ws.url("http://" + request.host + "/paragraph/").post(Map("xml" -> Seq(xml.xml))).map { response =>
Ok(response.body)
}
}else {
ws.url("http://" + request.host + "/").get().map { response =>
Ok(Html(response.body))
}
}
}
val xmlForm = Form(
mapping(
"xml" -> nonEmptyText
)(UserXML.apply)(UserXML.unapply)
)
}
示例6: Views
//设置package包名称以及导入依赖的类
package views
import play.twirl.api.Html
object Views {
def getLoaderHtml: Html = Html {
s"""
|<div class="preloader-wrapper big active">
| <div class="spinner-layer spinner-blue-only">
| <div class="circle-clipper left">
| <div class="circle"></div>
| </div><div class="gap-patch">
| <div class="circle"></div>
| </div><div class="circle-clipper right">
| <div class="circle"></div>
| </div>
| </div>
| </div>
|
""".stripMargin
}
def gmailButton: Html = Html {
s"""
|<a id="gmail_signin" class="waves-effect waves-light btn deep-purple"><i class="material-icons left">mail</i>Signin with Gmail</a>
""".stripMargin
}
}
示例7: 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
}
}
示例8: genericInput
//设置package包名称以及导入依赖的类
package views.html.htmlForm.bootstrap3
import play.twirl.api.Html
import views.html.helper.FieldElements
object genericInput {
def apply(elements: FieldElements): Html = Html {
s"""<div class="control-group ${ if (elements.hasErrors) "error" else "" }">
| <label for="${ elements.id }" class="control-label">${ elements.label }</label>
| <div class="controls">
| ${ elements.input }
| <span class="help-inline">${ elements.errors.mkString(", ") }</span>
| </div>
|</div>
|""".stripMargin
}
}
示例9: 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)
}
}
}
示例10: InputterTest
//设置package包名称以及导入依赖的类
import org.junit.runner.RunWith
import org.scalatest.Matchers._
import org.scalatest._
import org.scalatest.junit.JUnitRunner
import play.twirl.api.Html
import views.html.htmlForm.bootstrap3._
import views.html.htmlForm.bootstrap3.HtmlForm._
@RunWith(classOf[JUnitRunner])
class InputterTest extends WordSpec with MustMatchers with EitherValues with OptionValues {
"toHtml" should {
"work" in {
"string".toHtml shouldBe Html("string")
}
}
"dataAttrs" should {
"work" in {
def dataAttrs(data: List[(String, String)]) = data.map { case (n, v) => s"data-$n='$v'" }.mkString(" ", " ", " ")
dataAttrs(List("x" -> "y")) shouldBe " data-x='y' "
dataAttrs(List("x" -> "y", "a" -> "b")) shouldBe " data-x='y' data-a='b' "
}
}
}
示例11: Mailer
//设置package包名称以及导入依赖的类
package utils.mail
import models.daos.user.User
import play.api.i18n.Messages
import play.twirl.api.Html
import views.html.mails
object Mailer {
implicit def html2String(html: Html): String = html.toString
def welcome(user: User, identifier: String, pwd: String)(implicit ms: MailService, m: Messages) {
ms.sendEmailAsync(user.email)(
subject = Messages("web.mail.welcome.subject"),
bodyHtml = mails.welcome(user.firstName, identifier, pwd),
bodyText = mails.welcomeTxt(user.firstName, identifier, pwd)
)
}
def forgotPassword(email: String, link: String)(implicit ms: MailService, m: Messages) {
ms.sendEmailAsync(email)(
subject = Messages("web.mail.forgotpwd.subject"),
bodyHtml = mails.forgotPassword(email, link),
bodyText = mails.forgotPasswordTxt(email, link)
)
}
def emailValidation(email: String, link: String, name: String)(implicit ms: MailService, m: Messages) {
val siteUrl = Messages("web.mail.sign")
ms.sendEmailAsync(email)(
subject = Messages("web.mail.validation.subject", siteUrl),
bodyHtml = mails.emailValidation(name, link, siteUrl),
bodyText = mails.emailValidationTxt(name, link, siteUrl)
)
}
}
示例12: OrderController
//设置package包名称以及导入依赖的类
package controllers
import models.Order
import play.api.libs.json.{Json, Reads}
import play.api.mvc.{Action, Controller}
import play.twirl.api.Html
import services.{OrderService, PlacedOrders}
import scala.concurrent.{ExecutionContext, Future}
class OrderController(orderService: OrderService,
placedOrders: PlacedOrders)(
implicit ec: ExecutionContext)
extends Controller {
def ordersGet = Action {
Ok(Json.toJson(placedOrders.allOrders.get))
}
def ordersPost =
Action.async(parse.json(oneOrManyOrders)) { request =>
val orders: List[Order] = request.body
Future
.traverse(orders)(orderService.saveNew)
.map(list => Ok)
}
val oneOrManyOrders: Reads[List[Order]] =
implicitly[Reads[Order]]
.map(List(_))
.orElse(implicitly[Reads[List[Order]]])
def index = Action {
Ok(Html(
"<h1>Welcome</h1><p>Your new application is ready.</p>"))
}
}
示例13: TemplatePageMarshalling
//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.marshalling.Marshalling._
import akka.http.scaladsl.marshalling.ToResponseMarshaller
import akka.http.scaladsl.model._
import scala.concurrent.Future
import play.twirl.api.Html
object TemplatePageMarshalling {
private def getHtml(html: Html, charset: HttpCharset) = HttpResponse(
entity = HttpEntity(
ContentType.WithCharset(MediaTypes.`text/html`, charset),
html.body
)
)
def marshaller: ToResponseMarshaller[Html] = Marshaller(
implicit exeCtxt => html => Future.successful(
WithOpenCharset(MediaTypes.`text/html`, getHtml(html, _)) :: Nil
)
)
}
示例14: HomeController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import akka.actor.{ActorSystem, Props}
import models._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.i18n._
import play.api.mvc._
import play.twirl.api.Html
import views.html
import workers.Master
import workers.Master.Tick
class HomeController @Inject() (
actorSystem: ActorSystem,
configuration: play.api.Configuration,
fundsService: FundsService,
val messagesApi: MessagesApi)
extends Controller with I18nSupport {
val master = actorSystem.actorOf(Props(new Master(configuration, fundsService)), "master")
def index = Action { Ok(html.main(Html("Start searching... e.g. /list?filter=Pite?ti&from=0&size=10"))) }
def list(filter: String, from: Int, size: Int) = Action.async { implicit request =>
fundsService.find(filter, from, size).map(result => Ok(html.main(Html(result.toString))))
}
def refreshData() = Action.async { request =>
fundsService.deleteAll().map { _ =>
master ! Tick
Ok(html.main(Html("Refreshing ... It may take a while")))
}
}
}
示例15: FrontendGlobal
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.buildanddeploy
import java.io.File
import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import play.api.Mode._
import play.api.mvc.Request
import play.api.{Application, Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.play.audit.filters.FrontendAuditFilter
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.frontend.bootstrap.DefaultFrontendGlobal
import uk.gov.hmrc.play.http.logging.filters.FrontendLoggingFilter
import uk.gov.hmrc.play.filters.MicroserviceFilterSupport
import play.api.i18n.Messages.Implicits._
import play.api.Play.current
object FrontendGlobal
extends DefaultFrontendGlobal {
override val auditConnector = FrontendAuditConnector
override val loggingFilter = LoggingFilter
override val frontendAuditFilter = AuditFilter
override def onStart(app: Application) {
super.onStart(app)
ApplicationCrypto.verifyConfiguration()
}
override def standardErrorTemplate(pageTitle: String, heading: String, message: String)(implicit rh: Request[_]): Html =
uk.gov.hmrc.buildanddeploy.views.html.error_template(pageTitle, heading, message)
override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")
}
object ControllerConfiguration extends ControllerConfig {
lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}
object LoggingFilter extends FrontendLoggingFilter with MicroserviceFilterSupport {
override def controllerNeedsLogging(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsLogging
}
object AuditFilter extends FrontendAuditFilter with RunMode with AppName with MicroserviceFilterSupport {
override lazy val maskedFormFields = Seq("password")
override lazy val applicationPort = None
override lazy val auditConnector = FrontendAuditConnector
override def controllerNeedsAuditing(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsAuditing
}