Home > Web Front-end > HTML Tutorial > Golang 1.6: text/template内进行HTML/JavaScript/URL转义处理_html/css_WEB-ITnose

Golang 1.6: text/template内进行HTML/JavaScript/URL转义处理_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:19:05
Original
1648 people have browsed it

本文针对版本 Golang 1.6

首先Go中有两个模板package,一个是 html/template,它可以尝试解析HTML并在适当的地方做编码,另一个是 text/template,从名字是也可以看出来,这个就是基于纯文本的模板处理,因此如果需要编码转义,则需要手动加函数,文档 在这里。模板中的函数调用格式是:

functionName [Argument...]
Copy after login

text/template中很多预定义函数,这里我们关注HTML, JavaScript和URL的转义,分别对应 html, js和 urlquery这三个函数,所以使用这三个函数,然后在后面加上参数即可。

完整示例代码:

package mainimport (    "bytes"    "fmt"    "text/template")func main() {    t := template.Must(template.New("test").Parse("原始:{{.}}\nHTML:{{html .}}\nJS:{{js .}}\nURL:{{urlquery .}}"))    buffer := &bytes.Buffer{}    err := t.Execute(buffer, "刘 123 <> \"")    if err != nil {        panic(err)    }    fmt.Print(buffer.String())}
Copy after login

输出:

原始:刘 123 <> "HTML:刘 123 <> "JS:刘 123 \x3C\x3E \"URL:%E5%88%98+123+%3C%3E+%22
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template