回答

收藏

是否可以使用标准库在 Go 中嵌套模板?

技术问答 技术问答 315 人阅读 | 0 人回复 | 2023-09-12

我如何在 python 运行时获得像 Jinja 嵌套模板。TBC 我的意思是,我如何让一堆模板继承自一个基本模板,只在基本模板块中归档,就像 Jinja/django-templates 那样。是否可以仅html/template使用标准库。. X" n$ d: N2 s+ G! q- H# w' a2 Z
假如不可能,我的选择是什么?Mustache 似乎是一个选择,但我会错过那些好的微妙功能吗?html/template比如上下文敏感的转义?还有哪些选择?
- B, Z4 R. k$ e1 J5 I6 ]2 s# v. L3 z                                                                ! c3 P9 O( k  B3 ~. M
    解决方案:                                                                ' `) D, @2 a9 Q- c% u( _
                                                                是的,这是可能的。Ahtml.Template它实际上是一组模板文件。如果您执行此集中定义块,它可以访问此集中定义的所有其他块。0 t. {+ {  a1 e: p4 z3 r2 K5 }) p
如果你创建了这样一个模板集的地图,它基本上是 Jinja / Django 提供的灵活性。唯一的区别是html/template包不能直接访问文件系统,所以你必须自己分析和组合模板。
5 ^- Q9 f; [  B3 R2 y/ ]考虑以下两个不同的页面(index.html”和“other.html)例子,他们都继承了base.html”:
4 c8 Z: e) ?  a! Z# J8 E: e2 N
    // Content of base.html:{{define "base"}}  {{template "head" .}}  {{template "body" .}}{{end}}// Content of index.html:{{define "head"}}index{{end}}{{define "body"}}index{{end}}// Content of other.html:{{define "head"}}other{{end}}{{define "body"}}other{{end}}/ [0 D, G1 g$ q
以下模板集地图:
( ^3 v: {8 }1 ?8 b8 M. P/ S) K
    tmpl := make(map[string]*template.Template)tmpl["index.html"] = template.Must(template.ParseFiles("index.html","base.html"))tmpl["other.html"] = template.Must(template.ParseFiles("other.html","base.html"))
    & I7 P- T  ~3 a6 o3 X" Q
你现在可以通过调用来呈现你的index.html”页面
2 T+ `- c0 [, z  ~5 D
    tmpl["index.html"].Execute("base",data)
    8 y7 P( g, D  P8 Q# S) Z( X3 u8 k
你可以通过调用来呈现你的other.html”页面
6 }" ^! Y9 E& K( T2 \) {) X$ ^; R& e
    tmpl["other.html"].Execute("base",data)$ E3 x1 g% S# U( s. M6 B
甚至可以使用一些技能(如模板文件的一致命名协议)tmpl地图自动生成。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则