英文:
Unescape css input in HTML
问题
如何对 HTML 进行反转义?
我正在将一个 CSS 文件传递到 HTML 中,像这样:
<style>{{.file}}</style>
但是我得到的结果是:
<style>ZgotmplZ</style>
我尝试使用 template.HTML(data) 对字段进行包装,但没有起作用。
英文:
How do I unescape html?
I'm passing a css file into html like this
<style>{{.file}}</style>
I get this
<style>ZgotmplZ</style>
I've tried wrapping the field with template.HTML(data), didn't work.
答案1
得分: 4
Go的HTML模板包可以正确转义CSS。引用自模板包的文档:
> 转义是有上下文的,因此操作可以出现在JavaScript、CSS和URI的上下文中。
"ZgotmplZ"
是一个特殊值,如果你尝试包含的值在上下文中是无效或不安全的,它将被用作替代。
所以问题在于你尝试包含的CSS值是不安全的。首先尝试一些简单的东西,看看是否有效,比如:
body {background-color: #000}
在文档中找到了关于"ZgotmplZ"
的讨论(在ErrorCode
类型中),引用如下:
"ZgotmplZ"
的解释:
示例模板:
<img src="{{.X}}">
其中{{.X}}的值为`javascript:...`
讨论:
`"ZgotmplZ"`是一个特殊值,表示不安全的内容在运行时进入了CSS或URL上下文。示例的输出将是
<img src="#ZgotmplZ">
如果数据来自可信源,请使用内容类型来免除它的过滤:URL(`javascript:...`)。
解决方案
由于你尝试插入的代码是在CSS代码的上下文中而不是HTML中,你不能/不应该使用template.HTML(data)
。
有一个预定义的类型CSS
,用于安全地包含来自可信源的CSS代码,例如你指定的CSS代码,而不是来自用户填写的HTML表单。示例:
var safeCss = template.CSS(`body {background-image: url("paper.gif");}`)
然后将safeCss
值传递给你的模板参数。
英文:
The Go HTML template package properly excapes CSS. Quoting from the documentation of the template
package:
> The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts.
"ZgotmplZ"
is a special value, it is used as a replacement if the value you're trying to include is invalid or unsafe in the context.
So the problem is the CSS value you're trying to include, it is not safe. Try something simple first and see if it works, like:
body {background-color: #000}
Found the discussion of "ZgotmplZ"
in the documentation (at type ErrorCode
), quoting it:
"ZgotmplZ"
explanation:
Example Template:
<img src="{{.X}}">
where {{.X}} evaluates to `javascript:...`
Discussion:
"ZgotmplZ" is a special value that indicates that unsafe content reached a
CSS or URL context at runtime. The output of the example will be
<img src="#ZgotmplZ">
If the data comes from a trusted source, use content types to exempt it
from filtering: URL(`javascript:...`).
Solution
Since the code you try to insert is in the context of CSS code and not HTML, you can't/shouldn't use template.HTML(data)
.
There is a predefined type CSS
for safe inclusion of CSS code coming from trusted source, e.g. CSS code you specify and is not coming from an HTML form filled by the user. Example:
var safeCss = template.CSS(`body {background-image: url("paper.gif");}`)
And pass the safeCss
value to your template parameter.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论