【问题标题】:Play Framework 2.5 - Using "@" when generating html code in controller (html.apply)Play Framework 2.5 - 在控制器中生成 html 代码时使用“@”(html.apply)
【发布时间】:2017-07-26 05:53:24
【问题描述】:

在控制器中,我们正在创建一个字符串,当页面被渲染时,该字符串将被解释为 Html。每当字符串包含以“@”开头的 scala/twirl 代码时,它都会导致页面无法正确/完全呈现它。

控制器:

// render method
return ok(Html.apply(testButton()), testForm);

public String testButton() throws SQLException {
    result = "<input type='radio' id='@TestForm(\"TestID\").id'   
    name='@TestForm(\"TestID\").name'  value='5'  >" + "Test"; 
    return result;
}

Scala.html:

@(buttons: Html)(TestForm: Form[TestForm])

@buttons

它应该是什么样子:

<input type='radio' id='TestID' name='TestID'  value=5  >test

外观:

<input type='radio' id='@TestForm("TestID").id' name='@TestForm("TestID").name'  value='5'  >test

我们还使用其他示例对此进行了测试。问题似乎真的是@。也许解析器会解析站点一次,将@button 替换为我们的代码,但之后不会解析。我们也尝试用不同的方法(@@\@,没有@)转义@,但之后总是以纯文本结束。

在另一个@ 中渲染@ 的最简单方法是什么?

【问题讨论】:

  • 你为什么不想为按钮创建可重用视图而不是创建(我会说笨拙的)字符串?

标签: java html scala playframework twirl


【解决方案1】:

您不能在控制器中执行此操作。 @ 在编译时由 Twirl 编译器解析,但您试图在运行时引入它。它永远不会起作用。即使您可以让它工作,这也不是一个好主意。它通过将控制器代码与表示代码混为一谈来打破 MVC 范式。

这应该是另一个 Twirl 视图,类似于:

// I don't know what TestForm is, so this is a guess
// that it exists in the controller and needs to be passed in
@(TestForm: Form) 

<input
  type='radio'
  id='@TestForm("TestID").id'   
  name='@TestForm("TestID").name'  value='5'  
>

【讨论】:

  • 感谢您的洞察力。但是我们应该如何用灵活的值来称这个视图为灵活的次数呢?
  • 这是什么意思? Form 是一个非常普通的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
相关资源
最近更新 更多