在Play 2.0视图中转义JavaScript字符串? [英] Escape a JavaScript string in Play 2.0 view?

查看:77
本文介绍了在Play 2.0视图中转义JavaScript字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Play 2.0的视图中,是否有一种简便的方法可以将字符串转义为JavaScript字符串?例如,下面是一个简单的视图,该视图在onclick中创建一个带有确认框的链接:

Is there an easy way to escape a string to be used as a JavaScript string in a view in Play 2.0? For example, here's a simple view that creates a link with a confirm box in onclick:

@(text:String,link:Call,message:String)
<a href="@link" onclick="return confirm('@message');">@text</a>

如果消息中包含换行符或单引号,则该操作将失败.最好的方法是什么?

That will fail if there are newlines or single quotes in message. What's the best way to do this?

推荐答案

您可以使用Apache Commons Lang:

You can use Apache Commons Lang:

@(text:String, link:Call, message:String)

@import org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript
<a href="@link" onclick="return confirm('@escapeEcmaScript(message)');">@text</a>

通过将模板添加到您的project/Build.scala文件中,可以避免显式导入模板:

You can avoid the explicit import in the template by adding it to your project/Build.scala file:

templatesImport += "org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript"

这篇关于在Play 2.0视图中转义JavaScript字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆