当前位置:网站首页>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>
边栏推荐
- crypto-js使用
- Detailed explanation of the crawler framework Scrapy
- return; represents meaning
- 从离线到实时对客,湖仓一体释放全量数据价值
- 金山打字通 官网 下载
- LeetCode 0149. 直线上最多的点数
- first unique character in characters
- 仿牛客网项目总结
- datagrip 报错 “The specified database userpassword combination is rejected...”的解决方法
- Using FiddlerScript caught poly FiddlerScript 】 【 download
猜你喜欢
实战演练 Navicat 中英文模式切换
Using FiddlerScript caught poly FiddlerScript 】 【 download
【音视频】srs直播平台搭建
Dialogue with the father of MySQL: One excellent programmer is worth 5 ordinary programmers
Qt Widget project loading example of qml
从零开始—仿牛客网讨论社区项目(一)
Offer brush questions - 1
matlab 风速模型 小波滤波
基于MATLAB的BP神经网络进行语音特征信号分类
Vim三种模式
随机推荐
Offer刷题——1
Leetcode第 304 场周赛
Three aspects of Ali: How to solve the problem of MQ message loss, duplication and backlog?
leetcode125 Verify palindrome string
The Bean's life cycle
Jupyter shortcuts
阿里三面:MQ 消息丢失、重复、积压问题,该如何解决?
基于MATLAB的BP神经网络进行语音特征信号分类
头歌MySQL数据库实训答案 有目录
LeetCode 0150. 逆波兰表达式求值
Induction jian hai JustFE 2022/07/29 team, I learned the efficient development summary (years)
问下 mysql向pg同步多个表的话 有什么好的方案吗?
Flip letters using string container
Why is the lightweight VsCode used more and more?Why eat my C drive 10G?How to Painlessly Clean VsCode Cache?Teach you how to lose weight for C drive
史上超强最常用SQL语句大全
企业员工人事管理系统(数据库课设)
响应式织梦模板园林景观类网站
2022.7.26 Mock Competition
旋度(7)连接失败localhost8080;连接拒绝了
Information system project managers must recite the work of the core test site (56) Configuration Control Board (CCB)