【问题标题】:Play framework template cannot escape URL播放框架模板无法转义 URL
【发布时间】:2016-05-06 01:21:43
【问题描述】:

我有这个 Play 模板,dynamicLink.scala.html...

@( urlWithQuotes: Html, id: Html, toClick: Html )

@uniqueId_With_Quotes() = {
    Html("\"" + (@id) + "_" + scala.util.Random.nextInt.toString + "\"")
}

@defining(uniqueId_With_Quotes()) { uniqueID =>
    <a id=@uniqueID class="dynamicLink" href=@urlWithQuotes> @toClick </a>

    <script><!--Do stuff with dynamic link using jQuery--></script>
}

它会生成一个带有一些 Javascript 的特殊链接。我这样渲染这个链接......

@dynamicLink(
    Html("@{routes.Controller.action()}"),
    Html("MyID"),
    Html("Click Me")
)

当我渲染它时,我得到...

<a id=
Html("\"" + (MyID) + "_" + scala.util.Random.nextInt.toString + "\"")
class="dynamicLink" href=@{routes.Controler.action()}> Click Me </a>

这不是我想要渲染的。我要渲染这个...

<a id="MyID_31734697" class="dynamicLink" href="/path/to/controller/action"> Click Me </a>

如何正确地使这个 HTML 转义?

* 采取 #2 - 用字符串替换 Html 参数 *

@(urlWithQuotes: String, id: String, toClickOn: String)

@uniqueId_With_Quotes() = {
    Html("\"" + (@id) + "_" + scala.util.Random.nextInt.toString + "\"")
}

@defining(uniqueId_With_Quotes) { uniqueID =>
    <a id=@uniqueID class="dynamicLink" href=@urlWithQuotes> @toClickOn </a>
    ...
}

随着...

@dynamicLink2(
"@{routes.Controller.action()}",
"MyID",
"Click Me"
)

渲染...

    <a id=
    Html("\"" + (MyID) + "_" + scala.util.Random.nextInt.toString + "\"")
 class="dynamicLink" href=@{routes.Controller.action()}> Click Me </a>
    <script>
        ...
    </script>

* 将 Html 更改为字符串不起作用 *

* 请注意,“@uniqueId_With_Quotes()”扩展为“Html("\"" + (MyID) + "_" + scala.util.Random.nextInt .toString + "\"") "。我希望它实际执行字符串连接。 *

另外,这应该是显而易见的,但我希望每个链接和随附的 jquery 都使用该链接唯一的 ID 呈现,并且我不希望控制器不必担心分配这些唯一 ID。我这样做的方法是为每个 id 附加一个随机数(尽管对视图进行计数可能会更好)。我需要在视图中有这种有状态的行为,因为我需要“dynamicLink”对控制器完全透明。

【问题讨论】:

    标签: scala templates playframework playframework-2.0 template-engine


    【解决方案1】:

    您是否尝试将变量用作字符串类型?

    @( urlWithQuotes: String, id: String, toClick: String )
    

    【讨论】:

    • 将 Html 更改为字符串不起作用。另外,我不知道什么时候应该使用 Html,什么时候应该使用 String(在用户表单之外,应该始终使用 String 来保护再次注入)
    【解决方案2】:

    我找到了解决方案。你必须传递一个 Call 对象。

        @dynamicLink(
        ({routes.Controller.action()}),
        "MyID",
        "Click Me"
        )
    

    将这些参数传递给...

    @(urlNoQuotes: Call, id: String = "", toClickOn: String = "")
    
    @uniqueId_With_Quotes() = @{
        Html("\"" + (id) + "_" + scala.util.Random.nextInt.toString + "\"")
    }
    
    @url() = @{
        Html("\"" + urlNoQuotes + "\"")
    }
    
    @defining( url() ) { processedURL =>
        @defining(uniqueId_With_Quotes()) { uniqueID =>
        ... 
        }
    }
    

    ^ 现在可以了。

    【讨论】:

      猜你喜欢
      • 2014-07-23
      • 2012-08-10
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      • 2014-09-19
      • 2014-04-18
      相关资源
      最近更新 更多