当前位置:网站首页>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>
边栏推荐
- More than 2022 cattle guest school game 4 yue
- 2022.7.27 Selected lectures on good topics
- LeetCode 0150. Reverse Polish Expression Evaluation
- crypto-js使用
- 仿牛客网讨论社区项目—项目总结及项目常见面试题
- 声音信号处理基频检测和时频分析
- 响应式织梦模板园林花卉类网站
- 响应式织梦模板园林景观类网站
- 【翻译】确保云原生通信的安全:从入口到服务网及更远的地方
- Practical training Navicat Chinese and English mode switching
猜你喜欢
特别数的和
Information system project managers must recite the work of the core test site (56) Configuration Control Board (CCB)
Datagrip error "The specified database userpassword combination is rejected..."Solutions
MATLAB程序设计与应用 2.5 MATLAB运算
从离线到实时对客,湖仓一体释放全量数据价值
从购买服务器到网站搭建成功保姆级教程~超详细
Motion analysis and parameter optimization of crank-slider mechanism
crypto-js uses
matlab wind speed model wavelet filtering
【FiddlerScript】利用FiddlerScript抓包保利威下载
随机推荐
The BP neural network based on MATLAB voice characteristic signal classification
【南瓜书ML】(task4)神经网络中的数学推导(更新ing)
爆肝3万字,最硬核丨Mysql 知识体系、命令全集 【建议收藏 】
Motion analysis and parameter optimization of crank-slider mechanism
torch
AspNet.WebApi.Owin custom Token request parameters
NUMPY
NIO编程
目标检测概述-上篇
05-SDRAM: Arbitration
rhcsa 第四天
torch
leetcode125 Verify palindrome string
上课作业(7)——#598. 取余运算(mod)
「面经分享」西北大学 | 字节 生活服务 | 一面二面三面 HR 面
奇葩问题 npm install 报错 gyp ERR
Srping bean in the life cycle
Windows taskbar icon abnormal solution
Introduction to the basic principles, implementation and problem solving of crawler
uva12326