在golang中执行没有引号的模板。

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

Execute template without quotes in golang

问题

我想使用noescape和无引号的方式执行模板,但是目前不支持noescape

有什么建议吗?还是我需要使用另一个模板引擎?谢谢!

代码在这里:http://play.golang.org/p/R-Ib5H9bXx

英文:

I'd like to execute template with noescape and no quotes, but noescape is not supported now.

Any suggestion or do I have to use another template engine? Thank you!

Code here: http://play.golang.org/p/R-Ib5H9bXx

答案1

得分: 4

你被鼓励将安全的JavaScript代码存储在类型**template.JS**中:

> type JS string
>
> JS封装了一个已知安全的EcmaScript5表达式,例如(x + y * z())。模板作者有责任确保类型化的表达式不会破坏预期的优先级,并且没有语句/表达式的歧义,例如传递一个表达式“{ foo: bar() }\n'foo'”,它既是一个有效的表达式,也是一个具有完全不同含义的有效程序。

所以,你需要对你的代码做唯一的更改:

type Var struct {
    Name  template.JS
    Value template.JS
}
英文:

You are encouraged to store safe Javascript in the type template.JS:

> type JS string
>
> JS encapsulates a known safe EcmaScript5 Expression,
> for example, (x + y * z()). Template authors are responsible for
> ensuring that typed expressions do not break the intended precedence
> and that there is no statement/expression ambiguity as when passing an
> expression like "{ foo: bar() }\n'foo'", which is both a valid
> Expression and a valid Program with a very different meaning.

So, the only change you need to do to your code is:

type Var struct {
    Name  template.JS
    Value template.JS
}

答案2

得分: 0

@ANisus的回答中还有一个小的补充。对于HTML(和CSS),也有一个类似的包装器。每当你尝试将HTML字符串传递到模板中时,它会被引用。因此,为了正确呈现安全的HTML,请使用以下代码:

yourHTML := "<strong>Hi!</strong>"
yourWrappedHTML := template.HTML(yourHTML)
// 将后者传递到你的模板中
英文:

A small addition to @ANisus answer. There is also a similar wrapper for HTML (and CSS). Whenever you try to pass an HTML string into a template, it gets quoted. So in order to render the safe HTML properly, use:

yourHTML := &quot;&lt;strong&gt;Hi!&lt;/strong&gt;&quot;
yourWrappedHTML := template.HTML(yourHTML)
// pass the later into your template

huangapple
  • 本文由 发表于 2014年8月5日 11:56:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/25130946.html
匿名

发表评论

匿名网友

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

确定