当前位置:网站首页>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>
边栏推荐
- MATLAB program design and application of MATLAB 2.5
- 信息系统项目管理师必背核心考点(五十六)配置控制委员会(CCB)的工作
- Classwork (7) - #598. remainder operation (mod)
- NUMPY
- sum of special numbers
- "By sharing" northwestern university life service | | bytes a second interview on three sides by HR
- 数据机构----线性表之单向链表
- Vim扩展内容
- crypto-js uses
- NUMPY
猜你喜欢

crypto-js使用

NIO编程

插入排序—直接插入排序和希尔排序

湖仓一体电商项目(一):项目背景和架构介绍

Zero-code website development tool: WordPress

Data organization -- singly linked list of the linear table

mysql中添加字段的相关问题

Qt Widget project loading example of qml

2022.7.26 模拟赛

Information system project managers must recite the work of the core test site (56) Configuration Control Board (CCB)
随机推荐
「游戏引擎 浅入浅出」4.1 Unity Shader和OpenGL Shader
LeetCode每日一题(309. Best Time to Buy and Sell Stock with Cooldown)
戴尔PowerEdge服务器R450 RAID配置步骤
曲柄滑块机构运动分析和参数优化
Dialogue with the father of MySQL: One excellent programmer is worth 5 ordinary programmers
Causes and solutions of lock table
leetcode125 Verify palindrome string
Dart exception details
"By sharing" northwestern university life service | | bytes a second interview on three sides by HR
Dell PowerEdge Server R450 RAID Configuration Steps
【一句话攻略】彻底理解JS中的回调(Callback)函数
R语言使用tidyquant包的tq_transmute函数计算持有某只股票的天、月、周收益率、ggplot2使用条形图可视化股票月收益率数据、使用百分比显示Y轴坐标数据、使用不同的色彩表征正负收益率
Zero-code website development tool: WordPress
crypto-js使用
Xiaobai's 0 Basic Tutorial SQL: An Overview of Relational Databases 02
Jupyter shortcuts
LeetCode 0149. Maximum number of points on a line
Jupyter shortcuts
JSON 与 JS 对象的区别
05-SDRAM:仲裁