当前位置:网站首页>The use of Golang: go template engine
The use of Golang: go template engine
2022-08-01 07:03:00 【ZzzWClock】
go模版引擎的使用
一.前言
import “html/template”
template包(html/template)实现了数据驱动的模板,用于生成可对抗代码注入的安全HTML输出.本包提供了和text/template包相同的接口,无论何时当输出是HTML的时候都应使用本包.
二.示例
- 使用html/templateParse the template file and pass parameters to the template file
- golang代码块
package mian
import (
"fmt"
"html/template"
"net/http"
)
// html处理器
func htmlHandle(w http.ResponseWriter, r *http.Request) {
// Parse a template file
// MustFunctions are used to wrap returns(*Template, error)的函数/方法调用,它会在err非nil时panic,Generally used for variable initialization:
// ParseFilesThe function creates a template and parses itfilenamesTemplate definitions in the specified file.The name of the returned template is the filename of the first file(不含扩展名),The content is the content of the first parsed file.至少要提供一个文件.如果发生错误,会停止解析并返回nil.
t := template.Must(template.ParseFiles("index.html"))
// Execute方法将解析好的模板应用到data上,并将输出写入wr.如果执行时出现错误,会停止执行,但有可能已经写入wr部分数据.模板可以安全的并发执行.
t.Execute(w, "I am a passage of words")
}
func main() {
// 路由器
http.HandleFunc("/html", htmlHandle)
// 开启server服务
http.ListenAndServe(":8081", nil)
}
- html代码块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p style="color: red;">I am a template file:{
{.}}</p>
</body>
</html>
边栏推荐
猜你喜欢
随机推荐
Explosive 30,000 words, the hardest core丨Mysql knowledge system, complete collection of commands [recommended collection]
AspNet.WebApi.Owin custom Token request parameters
旋度(7)连接失败localhost8080;连接拒绝了
小程序通过云函数操作数据库【使用get取数据库】
第5章——以程序方式处理MySQL数据表的数据
leetcode125 Verify palindrome string
crypto-js uses
Dell PowerEdge Server R450 RAID Configuration Steps
插入排序—直接插入排序和希尔排序
「面经分享」西北大学 | 字节 生活服务 | 一面二面三面 HR 面
R语言使用gt包和gtExtras包优雅地、漂亮地显示表格数据:gtExtras包的pad_fn函数与gt::fmt函数一起用于填充包含数值的特定列、对数据列的数值进行十进制对齐(从小数点对齐)
Jupyter shortcuts
matlab wind speed model wavelet filtering
金山打字通 官网 下载
JSON 与 JS 对象的区别
奇葩问题 npm install 报错 gyp ERR
mysql的行锁和间隙锁
如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法
How JS works
Matlab simulink particle swarm optimization fuzzy pid control motor pump