【问题标题】:Scala Play template vararg HtmlContentScala Play 模板 vararg HtmlContent
【发布时间】:2017-04-10 04:49:59
【问题描述】:

我在play 2.6 中有一个通用模板,我想传入可变数量的HtmlContents。我已经像这样定义了template(包括我所拥有的隐式参数,以防发生任何变化):

@(foo: String)(content: Html*)(implicit bar: Bar)

在模板方面,这很好用——我可以用for 剖析content 并根据需要渲染它。但是,我还没有找到一种从底层模板调用变量参数的干净方法。

例如,我有一个名为“Baz”的视图:

@(something: String)(implicit bar: Bar)

在其中,我尝试使用多个 Html 参数调用 template。我尝试了以下方法:

@template("fooString"){{123},{abc}}
and
@template("fooString")({123}, {abc})
and
@template("fooString"){{123}, {abc}})

以及各种其他排列,但在封闭括号内,它似乎将所有内容逐字解释为HtmlContent vararg 中的单个参数。

但是,这最终按我的预期工作,传递了多个HtmlContents

@template("fooString")(Html("123"), Html("abc"))

这样行得通,我可以对一个大的 Html 块使用三引号内插字符串——但似乎应该有一种更清洁的方法来做到这一点,而且字符串内插很危险,因为它不这样做html 转义。

有没有办法使用 { 封闭的语法来做到这一点?我想了解更多在底层实际发生的事情,以及 play 如何解析和生成括号中的 HtmlContent。

【问题讨论】:

  • 您的Html(...) 方法对我来说看起来非常干净和明确。不过,Twirl source code 可能是一个尝试深入研究您的问题的地方。
  • 我发布的答案中有任何 cmets 吗?

标签: html scala playframework variadic-functions twirl


【解决方案1】:

所以考虑你有以下模板

// main.scala.html
@(title: String)(contents: Html*)

您可以通过多种方式调用此模板

选项 #1

这是您已经在问题中发布的内容

@main("This is a title")(Html("abc"), Html("123"))

选项 #2

@html1 = {
    Hello
}
@html2 = {
    <div>Tarun</div>
}

@main("This is a title")(html1, html2)

选项#3

@main("This is a title")(Html(<div>Tarun
</div>.toString), Html(<div>
Lalwani
</div>.toString))

选项 #4

这不是完全相同的选项,但需要更改模板签名本身

@(title: String)(contents: List[String])  

然后像下面这样调用它

@main("This is a title")(List(
  """<div>
     Tarun
    </div>
  """, """Hello"""))

选项 #5

这需要代码文件,并且已经在另一个 SO 线程上得到回答

Paul Draper's回复Why doesn't this pass multiple HTML parameters to template

【讨论】:

  • 对否决票有什么解释吗?最好用downvote发表评论
猜你喜欢
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多