英文:
Go lang templates: always quotes a string and removes comments
问题
这段Go代码总是引用一个字符串:http://play.golang.org/p/8k4s8dv2PE 在模板中 - 你可以看到结果。我如何生成var currentUser = null
?请注意,它还会删除代码中的所有注释!它是如何调整的?这个问题是我之前的问题的延续:https://stackoverflow.com/questions/14150985/go-quoted-string-in-templates。
英文:
This Go code always quotes a string: http://play.golang.org/p/8k4s8dv2PE in the template - you can see results. How can I generate var currentUser = null
? Note it also removes all comments from the code! How is it tuned up? This question is continuation of my https://stackoverflow.com/questions/14150985/go-quoted-string-in-templates.
答案1
得分: 10
html/template
包专门设计用于转义值。在您的情况下,您正在尝试传递JavaScript代码,而不是一个简单的值。您可以通过将UserEmail
的类型更改为template.JS
来实现这一点。这种类型包装了一个string
,并表达了这个值是有效的JavaScript,并且在JavaScript上下文中使用时应该直接替换(不带引号)的意图。
这个版本的代码正是这样做的:http://play.golang.org/p/aNGnFMyY1O
英文:
The html/template
package is expressly designed to escape values. In your case, you're trying to pass JavaScript code in, rather than a simple value. You can accomplish this by changing the type of UserEmail
to that of template.JS
. This type wraps a string
and expresses the intent that this value is valid JavaScript and should be substituted directly (without quotes) when used in a JavaScript context.
This version of the code does precisely that: http://play.golang.org/p/aNGnFMyY1O
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论