Go lang templates: always quotes a string and remo

2019-05-12 09:22发布

问题:

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 Go: quoted string in templates.

回答1:

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