当前位置:网站首页>Golang:go模版引擎的使用
Golang:go模版引擎的使用
2022-08-01 06:50:00 【ZzzWClock】
go模版引擎的使用
一.前言
import “html/template”
template包(html/template)实现了数据驱动的模板,用于生成可对抗代码注入的安全HTML输出。本包提供了和text/template包相同的接口,无论何时当输出是HTML的时候都应使用本包。
二.示例
- 使用html/template解析模版文件并且传递参数至模版文件

- golang代码块
package mian
import (
"fmt"
"html/template"
"net/http"
)
// html处理器
func htmlHandle(w http.ResponseWriter, r *http.Request) {
// 解析一个模版文件
// Must函数用于包装返回(*Template, error)的函数/方法调用,它会在err非nil时panic,一般用于变量初始化:
// ParseFiles函数创建一个模板并解析filenames指定的文件里的模板定义。返回的模板的名字是第一个文件的文件名(不含扩展名),内容为解析后的第一个文件的内容。至少要提供一个文件。如果发生错误,会停止解析并返回nil。
t := template.Must(template.ParseFiles("index.html"))
// Execute方法将解析好的模板应用到data上,并将输出写入wr。如果执行时出现错误,会停止执行,但有可能已经写入wr部分数据。模板可以安全的并发执行。
t.Execute(w, "我是被传递的一段话")
}
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;">我是一个模版文件:{
{.}}</p>
</body>
</html>
边栏推荐
- Create, modify and delete tables
- 爬虫基本原理介绍、实现以及问题解决
- Using FiddlerScript caught poly FiddlerScript 】 【 download
- Offer刷题——1
- 2022.7.27 Selected lectures on good topics
- 从购买服务器到网站搭建成功保姆级教程~超详细
- 爆肝3万字,最硬核丨Mysql 知识体系、命令全集 【建议收藏 】
- More than 2022 cattle guest school game 4 yue
- flinkcdc对mysql的date字段类型转化有什么解决思路么
- 选择排序—直接选择排序和堆排序
猜你喜欢
随机推荐
NUMPY
Talk about the bugs in using for in to traverse the array in js
Create, modify and delete tables
旋度(7)连接失败localhost8080;连接拒绝了
ORACLE 实现另外一个用户修改包(package)
【视觉SLAM十四讲】第一章理论详解
NIO编程
戴尔PowerEdge服务器R450 RAID配置步骤
Jupyter shortcuts
图像基本操作的其他内容
matlab simulink 粒子群优化模糊pid控制的电机泵
LeetCode 0150. Reverse Polish Expression Evaluation
Dart exception details
牛客刷SQL---2
我三本学历,五面阿里,被面试官“供”着出来了,拿了33*15的Offer
Solve the problem of page flicker caused by browser scroll bars
Induction jian hai JustFE 2022/07/29 team, I learned the efficient development summary (years)
对于升级go1.18的goland问题
return;代表含义
深度比较两个对象是否相同








