Go语言模板:始终引用字符串并删除注释

huangapple go评论96阅读模式
英文:

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

huangapple
  • 本文由 发表于 2013年1月9日 08:24:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/14226416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定