本文整理汇总了Scala中play.twirl.api.Html类的典型用法代码示例。如果您正苦于以下问题:Scala Html类的具体用法?Scala Html怎么用?Scala Html使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Html类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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>""")
}
开发者ID:Driox,项目名称:play-app-seed,代码行数:46,代码来源:assets.scala
示例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)
}
}
开发者ID:Driox,项目名称:play-app-seed,代码行数:59,代码来源:CustomTag.scala
示例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
}
开发者ID:hmrc,项目名称:trust-registration-frontend,代码行数:58,代码来源:frontendGlobal.scala
示例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)
}
}
开发者ID:luissalda1995,项目名称:generador-vistas,代码行数:42,代码来源:Utils.scala
示例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)
)
}
开发者ID:Peantab,项目名称:paragraph-framework,代码行数:57,代码来源:NavigationController.scala
示例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
}
}
开发者ID:pamu,项目名称:blog,代码行数:31,代码来源:Views.scala
示例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
}
}
开发者ID:mslinn,项目名称:html-form-scala,代码行数:22,代码来源:password.scala
示例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
}
}
开发者ID:mslinn,项目名称:html-form-scala,代码行数:18,代码来源:genericInput.scala
示例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)
}
}
}
开发者ID:mslinn,项目名称:html-form-scala,代码行数:24,代码来源:checkbox.scala
示例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' "
}
}
}
开发者ID:mslinn,项目名称:html-form-scala,代码行数:26,代码来源:InputterTest.scala
示例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)
)
}
}
开发者ID:seyuf,项目名称:play-swagger-silhouette-actors,代码行数:40,代码来源:mailer.scala
示例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>"))
}
}
开发者ID:leanovate,项目名称:contoso-conference-manager,代码行数:40,代码来源:OrderController.scala
示例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
)
)
}
开发者ID:ICOS-Carbon-Portal,项目名称:doi,代码行数:26,代码来源:TemplatePageMarshalling.scala
示例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")))
}
}
}
开发者ID:radusw,项目名称:eu_funds,代码行数:38,代码来源:HomeController.scala
示例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
}
开发者ID:hmrc,项目名称:build-and-deploy,代码行数:57,代码来源:frontendGlobal.scala
示例16: Html5AudioRenderer
//设置package包名称以及导入依赖的类
package gitbucket.html5media
import gitbucket.core.plugin.{Renderer, RenderRequest}
import play.twirl.api.Html
class Html5AudioRenderer extends Renderer {
def render(request: RenderRequest): Html = {
Html(s"""<audio src="${request.context.request.getRequestURL}?raw=true" controls autoplay/>""")
}
}
class Html5VideoRenderer extends Renderer {
def render(request: RenderRequest): Html = {
Html(s"""<video src="${request.context.request.getRequestURL}?raw=true" autoplay width="100%"/>""")
}
}
class PDFRenderer extends Renderer {
def render(request: RenderRequest): Html = {
Html(
s"""<object data="${request.context.request.getRequestURL}?raw=true" width="100%" height="700">
|<p>Your browser does not support render inline PDF. Please download from this
| <a href="${request.context.request.getRequestURL}?raw=true">Link</a></p>
|</object>""".stripMargin)
}
}
开发者ID:kounoike,项目名称:gitbucket-html5media-plugin,代码行数:27,代码来源:Html5Renderer.scala
示例17: ContactsController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import models.Contact
import play.api.mvc.{AnyContent, Action, Controller}
import play.twirl.api.Html
class ContactsController @Inject() extends Controller {
private def withinLayout(html: Html) = views.html.layouts.application(html)
def index: Action[AnyContent] = Action {
val contacts = Contact.all
Ok(withinLayout(views.html.contacts.index(contacts)))
}
def create: Action[AnyContent] = Action { Ok("") }
def show(id: Long): Action[AnyContent] = Action { Ok("") }
def update(id: Long): Action[AnyContent] = Action { Ok("") }
def delete(id: Long): Action[AnyContent] = Action { Ok("") }
}
开发者ID:denyago,项目名称:play_contacts_app,代码行数:22,代码来源:ContactsController.scala
示例18: OpenGraph
//设置package包名称以及导入依赖的类
package lila.app
package ui
import org.apache.commons.lang3.StringEscapeUtils.escapeHtml4
import play.twirl.api.Html
case class OpenGraph(
title: String,
description: String,
url: String,
`type`: String = "website",
image: Option[String] = None,
siteName: String = "chess-online.com",
more: List[(String, String)] = Nil
) {
def html = Html(og.str + twitter.str)
object og {
private def tag(name: String, value: String) =
s"""<meta property="og:$name" content="${escapeHtml4(value)}"/>"""
private val tupledTag = (tag _).tupled
def str = List(
"title" -> title,
"description" -> description,
"url" -> url,
"type" -> `type`,
"site_name" -> siteName
).map(tupledTag).mkString +
image.?? { tag("image", _) } +
more.map(tupledTag).mkString
}
object twitter {
private def tag(name: String, value: String) =
s"""<meta name="twitter:$name" content="${escapeHtml4(value)}"/>"""
private val tupledTag = (tag _).tupled
def str = List(
"card" -> "summary",
"title" -> title,
"description" -> description,
"site" -> "@playschess"
).map(tupledTag).mkString +
image.?? { tag("image", _) } +
more.map(tupledTag).mkString
}
}
开发者ID:DrNixx,项目名称:line,代码行数:54,代码来源:OpenGraph.scala
示例19: toJson
//设置package包名称以及导入依赖的类
package lila.app
package templating
import play.api.libs.json._
import play.twirl.api.Html
import lila.api.Context
trait JsonHelper {
def toJson[A: Writes](map: Map[Int, A]): String = Json stringify {
Json toJson {
map mapKeys (_.toString)
}
}
def toJson[A: Writes](a: A): String = Json stringify {
Json toJson a
}
def J = Json
def htmlOrNull[A, B](a: Option[A])(f: A => Html) = a.fold(Html("null"))(f)
def jsOrNull[A: Writes](a: Option[A]) = Html {
a.fold("null")(x => toJson(x))
}
def jsUserId(implicit ctx: Context) = Html {
ctx.userId.fold("null")(id => s""""$id"""")
}
}
开发者ID:DrNixx,项目名称:line,代码行数:33,代码来源:JsonHelper.scala
示例20: Granter
//设置package包名称以及导入依赖的类
package lila.app
package templating
import play.twirl.api.Html
import lila.api.Context
import lila.forum.Post
trait ForumHelper { self: UserHelper with StringHelper =>
private object Granter extends lila.forum.Granter {
protected def userBelongsToTeam(teamId: String, userId: String): Fu[Boolean] =
Env.team.api.belongsTo(teamId, userId)
protected def userOwnsTeam(teamId: String, userId: String): Fu[Boolean] =
Env.team.api.owns(teamId, userId)
}
def isGrantedRead(categSlug: String)(implicit ctx: Context) =
Granter isGrantedRead categSlug
def isGrantedWrite(categSlug: String)(implicit ctx: Context) =
Granter isGrantedWrite categSlug
def authorName(post: Post) = post.userId match {
case Some(userId) => userIdSpanMini(userId, withOnline = true)
case None => Html(lila.user.User.anonymous)
}
def authorLink(
post: Post,
cssClass: Option[String] = None,
withOnline: Boolean = true
) = post.userId.fold(Html(lila.user.User.anonymous)) { userId =>
userIdLink(userId.some, cssClass = cssClass, withOnline = withOnline)
}
}
开发者ID:DrNixx,项目名称:line,代码行数:39,代码来源:ForumHelper.scala
注:本文中的play.twirl.api.Html类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论