首页 > 其他分享 >go 模板

go 模板

时间:2023-01-25 23:57:00浏览次数:38  
标签:template nil ParseFiles html Template go 模板

template.ParseFiles()
实现: func ParseFiles(filenames ...string) (*Template, error) { return parseFiles(nil, readFileOS, filenames...) }
func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
    return parseFiles(t, readFileOS, filenames...)
}

template.ParseFiles函数和ParseFiles方法都是调用底层函数parseFiles

func parseFiles(t *Template, readFile func(string) (string, []byte, error), filenames ...string) (*Template, error) {
    if err := t.checkCanParse(); err != nil {
        return nil, err
    }

    if len(filenames) == 0 {  //检查是否有模板文件名
        // Not really a problem, but be consistent.
        return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
    }
    for _, filename := range filenames {   //遍历模板文件名
        name, b, err := readFile(filename) //读取模板文件内容 
        if err != nil {
            return nil, err
        }
        s := string(b)        
        // First template becomes return value if not already defined,
        // and we use that one for subsequent New calls to associate
        // all the templates together. Also, if this file has the same name
        // as t, this file becomes the contents of t, so
        //  t, err := New(name).Funcs(xxx).ParseFiles(name)
        // works. Otherwise we create a new template associated with t.
        var tmpl *Template
        if t == nil {    //检查t是否为nil,为nil是template.ParseFiles函数调用
            t = New(name)  //若是nil则生成一个*Template实例,名字为第一个模板文件名
        }
        if name == t.Name() {//若t不为nil,为ParseFiles方法调用,检查所有的模板文件名
            tmpl = t     //是否有和t名字一样的,如果有则解析那个模板文件。
        } else {
            tmpl = t.New(name)
        }
        _, err = tmpl.Parse(s)
        if err != nil {
            return nil, err
        }
    }
    return t, nil
}

解析模板的几种方法:

①使用template.ParseFiles。模板名为第一模板文件名,使用t.Execute(w, data)使用模板只会使用执行第一个模板。

使用t.ExecuteTemplate(w, 模板文件名,data)可以指定使用哪个模板文件。

t, _ := template.ParseFiles("template2.html", "template1.html");
fmt.Println(t.Name())
//结果:template2.html

②先使用template.New(模板名)生成一个*Template实例,然后使用这个实例调用其ParseFiles()。New()中使用的模板名,要和传入ParseFiles()中的文件名中的一个对应,即解析了那个模板文件。

//template1.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{.}}
</body>
</html>
//template2.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ol>{{.}}</ol>
</body>
</html>
func main() {
    t := template.New("template2.html")
    fmt.Println(t.Name())    //输出t的模板名
    t, _ = t.ParseFiles("template2.html", "template1.html")
    t.Execute(os.Stdout, "hello")//输出内容
}

结果

template2.html    //输出的模板名
<!DOCTYPE html>      //输出的内容     
<html lang="en">          
<head>                    
    <meta charset="UTF-8">
    <title>Title</title>  
</head>
<body>
    <ol>hello</ol>
</body>
</html>

③解析字符串。使用*Template的方法Parse来解析字符串

func (t *Template) Parse(text string) (*Template, error)
func articlesCreateHandler(w http.ResponseWriter, r *http.Request) {
    html := `
<!DOCTYPE html>     
<html lang="en">          
<head>                    
    <meta charset="UTF-8">
    <title>Title</title>  
</head>
<body>
    <ol>{{.}}</ol>
</body>
</html>
`
t := template.New("tmpl")
t, _ = t.Parse(html)
t.Execute(w, "hello world")

模板动作

条件动作

 

标签:template,nil,ParseFiles,html,Template,go,模板
From: https://www.cnblogs.com/dadishi/p/17067468.html

相关文章

  • go mod init 之后 vscode报错gopls was not able to find modules in your workspace
    (27条消息)vscode报错packagexxxisnotinGOROOT(path)或者go:toaddmodulerequirementsandsums:gomodtidy_Kpdo的博客-CSDN博客上文是我在网上看了2天2夜,......
  • Install Go 1.19 in windows 11 & Ubuntu 20.04
    TheGoProgrammingLanguagehttps://go.dev/DownloadandinstallGo1.19withwingethttps://winget.run/pkg/GoLang/Go.1.19注意:需要使用VPN代理,从google下载。ht......
  • 怎么学习 Golang
    怎么学习Golang?-知乎https://www.zhihu.com/question/23486344Golang之go命令用法-腾讯云开发者社区-腾讯云https://cloud.tencent.com/developer/article/120021......
  • 动态规划 背包问题算法模板
    一篇文章吃透背包问题!(细致引入+解题模板+例题分析+代码呈现)  https://leetcode.cn/problems/partition-equal-subset-sum/solution/yi-pian-wen-zhang-chi-tou-bei-b......
  • (20)go-micro微服务Elasticsearch使用
    目录一Elasticsearch介绍二Elasticsearch的主要功能及应用场景1.Elasticsearch主要具有如下功能:2.Elasticsearch的主要应用场景如下:三Elasticsearch核心概念四Elasti......
  • 基于Laravel9+Vue+ElementUI的管理系统模板源码
    项目介绍一款PHP语言基于Laravel9.x、Vue、ElementUI等框架精心打造的一款模块化、插件化、高性能的前后端分离架构敏捷开发框架,可用于快速搭建前后端分离后台管理系统,本......
  • typora+picGo腾讯云图床设置
    前言需求原因​ 大部分人在写博客都是使用的较为好看的markdown格式,而我们在本地编写markdown时其中的图片一般都是截图后粘贴的。这些图片其实都保存在了本地文件夹中,ma......
  • 对质数取模结果(扩展欧几里得算法模板)爬树甲壳虫
    问题描述有一只甲壳虫想要爬上一颗高度为 �n的树,它一开始位于树根,高度为 00,当它尝试从高度 �−1i−1 爬到高度为 �i 的位置时有 ��Pi​ 的概率会掉回树根,求它从树根爬......
  • Argo CD应用管理
    一个云原生应用程序通常包含多种Kubernetes资源类型,例如Deployment、ReplicaSet、Pod、PersistVolume、Service等,但在Kubernetes的原生能力下,并没有一个完整的概念可以直观......
  • Argo CD应用的更新和回滚
    ArgoCD是用于Kubernetes的声明式GitOps应用持续交付工具,相比于传统的DevOps应用持续交付模型,GitOps模型下的应用更新和回滚更加高效,那么在使用ArgoCD更新、交付应用之前,......