是否有必要将模板放入地图中以便在Go中重复使用? [英] Is it necessary to put templates into a map for reusing in Go?

查看:35
本文介绍了是否有必要将模板放入地图中以便在Go中重复使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要处理Web应用程序中的每个请求,有关模板的常规代码如下:

To deal with every request in a web application, the normal code about templates is like this:

t:= template.New("welcome")
t, _ = t.ParseFiles("welcome.tpl")
t.Execute(w, data)

我猜每次 ParseFiles 都花了很多钱.是否可以重复使用模板?因此,我对此进行了改进:

I guess ParseFiles every time cost a lot. Is it possible to reuse the template? So I improved it like this:

//templateMap := make(map[string][template])
//...
tplName :="welcome"
t := templateMap[tplName]
if t=nil{
    t:= template.New(tplName )
    t, _ = t.ParseFiles("welcome.tpl")
    templateMap[tplName] = t
}

t.Execute(w, data)

我想知道通过将模板放入地图或缓存来提高效率是可行还是可行的?我还想知道函数 Execute 是否是线程安全的?

I wonder it is feasible or practicable to improve efficiency by putting templates into a map or a cache? I also wonder the function Execute is thread safe or not?

func(t *模板)执行(wr io.Writer,数据接口{})(错误)

推荐答案

模板本身实际上可以充当模板的映射.这是我的工作:

A template can actually act as a map of templates by itself. Here's what I do:

我声明了一个全局模板变量:

I declare a global template variable:

var t = template.New("master")

除了用作其他模板的容器之外,我实际上没有使用主"模板.

I don't actually use the "master" template, except as a container for other templates.

然后,在我的应用启动时加载所有模板:

Then, I load all the templates when my app starts:

func init() {
    _, err := t.ParseGlob("templates/*.html")
    if err != nil {
        log.Fatalln("Error loading templates:", err)
    }
}

然后,当我想使用其中一个模板时,请按名称要求:

Then when I want to use one of the templates, I ask for it by name:

t.ExecuteTemplate(w, "user.html", data)

这篇关于是否有必要将模板放入地图中以便在Go中重复使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆