How to stop html template from escaping

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

How to stop html template from escaping

问题

我有一个HTML模板,我想要在模板之外插入一些JavaScript代码。在我的模板数据结构中,我创建了一个字符串字段JS string,并通过{{.JS}}调用它。问题是在浏览器中显示的所有内容都被转义了:

换行符是\n

<>分别被转义为\u003c\u003e

"被转义为\"

在模板内部相同的符号是正常的。如果我将我的JS字段打印到控制台上,也是正常的。我看到一些类似的问题通过使用template.HTML类型而不是string来解决。但在我的情况下,这根本不起作用。

编辑1

实际上的上下文是:

<script language="JavaScript">
    var options = {
        {{.JS}}
    };
</script>
英文:

I have an html template where i want to insert some JavaScript code from outside of template itself. In my template data struct i have created a string field JS string and call it with {{.JS}}. The problem is that everything in browser is escaped:

newlines are \n

< and > are \u003c and \u003e

" is \"

Same symbols inside of a template are fine. If I Print my JS field into console it is also fine. I have seen some similar problems solved by using template.HTML type instead of string. In my case it does not work at all.

EDIT 1

The actual context is

<script language="JavaScript">
    var options = {
        {{.JS}}
    };
</script>

答案1

得分: 13

要翻译的内容如下:

要么将字段的类型更改为template.JS,如下所示:

type Tmpl struct {
    // ...
    JS template.JS
}

要么声明一个简单的函数,将string转换为template.JS类型,如下所示:

func toJS(s string) template.JS {
    return template.JS(s)
}

然后使用Funcs方法注册该函数,并在模板中使用它,如下所示:

{{toJS .JS}}
英文:

Either change the field's type to template.JS like so:

type Tmpl struct {
    // ...
    JS template.JS
}

Or declare a simple function that converts a string to the template.JS type like so:

func toJS(s string) template.JS {
    return template.JS(s)
}

And then register the function with the Funcs method and use it in your template like so:

{{toJS .JS}}

答案2

得分: 4

尝试将JS的类型设置为template.JS

import "html/template"

type x struct {
        JS template.JS
}

可以在这里找到文档。

英文:

Try setting the type of JS to template.JS:

import "html/template"

type x struct {
        JS template.JS
}

Documentation can be found here.

huangapple
  • 本文由 发表于 2017年5月17日 02:33:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/44009102.html
匿名

发表评论

匿名网友

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

确定