Golang. html/template. How to put a unquoted string to <script>?

感情迁移 提交于 2019-12-24 01:46:40

问题


I have a template:

<script type="text/template" id="data-user">{{.User}}</script>

Where "User" is json string in URL encoding format. Something like

%7Bdata%22%3A%5B%7B%7D%7D

But default html/template put it inside quotes like

"%7Bdata%22%3A%5B%7B%7D%7D"

I tried that stuff from html/template godoc reference Context {{.}} After {{.}} O'Reilly: How are &lt;i&gt;you&lt;/i&gt;? <a title='{{.}}'> O&#39;Reilly: How are you? <a href="/{{.}}"> O&#39;Reilly: How are %3ci%3eyou%3c/i%3e? <a href="?q={{.}}"> O&#39;Reilly%3a%20How%20are%3ci%3e...%3f <a onx='f("{{.}}")'> O\x27Reilly: How are \x3ci\x3eyou...? <a onx='f({{.}})'> "O\x27Reilly: How are \x3ci\x3eyou...?" <a onx='pattern = /{{.}}/;'> O\x27Reilly: How are \x3ci\x3eyou...\x3f

But I haven't had success. Appreciate your help


回答1:


Thank you! I found solution. There are template.JS type. I converted string to template.JS and it works.

See this example:

t := template.Must(template.New("").Parse(`<script>{{.}}</script>` + "\n"))
t.Execute(os.Stdout, "%7Bdata%22%3A%5B%7B%7D%7D")
t.Execute(os.Stdout, template.JS("%7Bdata%22%3A%5B%7B%7D%7D"))

Output:

<script>"%7Bdata%22%3A%5B%7B%7D%7D"</script>
<script>%7Bdata%22%3A%5B%7B%7D%7D</script>

Try these on the Go Playground.



来源:https://stackoverflow.com/questions/36507836/golang-html-template-how-to-put-a-unquoted-string-to-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!