Go模板将数据从一个模板传递到另一个模板的方法

huangapple go评论71阅读模式
英文:

Go template Passing data from one to another

问题

我必须处理一个Go模板文件。我需要从一个模板传递一些值到另一个模板。例如,模板A有两个变量,分别是.Name和.Type。这些值通过go代码使用ctx.Data传递。模板A引用了模板B,代码如下:

{{ template "B" . }}

但是在模板B中,.Name和.Type的名称不同。我不能更改模板B的变量引用,因为模板B直接使用这些变量。模板B的代码如下:

用户名:{{ .UserName }}
类型:{{ .UserType }}

现在我的问题是,如何将模板A中的.Name更改为.UserName?

{{ template "B" .Name as .UserName }}

是否有类似这样的语法?

英文:

I have to Go Template file. I need to pass some value from one template to another. IE

Template A have two variable with .Name and .Type. The values are passing from go code with ctx.Data. Template A references Template B with

{{ template "B" . }}

But in Template B. .Name and .Type are not having the same name. I can not change Template B s variable references because Tempalte B is used directly with those variable.
Template B looks like this.

Username : {{ .UserName }}
Type : {{ .UserType }}

Now my question is how can i change the .Name in template A to .UserName?

{{ tempalte "B" .Name as .UserName }}

is there something like this????

答案1

得分: 1

很抱歉,Go语言的text/template或html/template包的当前版本无法实现这一点。

你需要在Go端将“Name”和“UserName”附加到ctx.Data上,以便在模板B中以这些确切的名称访问它们。

你可以考虑使用pongo2,这是一个类似于Django的Go模板(https://github.com/flosch/pongo2)。

pongo2中有关于你特定用例的文档,可以在这里找到:https://github.com/flosch/pongo2/blob/master/template_tests/includes.tpl

英文:

Unfortunately, this is not possible with current version of Go's text/template or html/template package.

You would need to append "Name" and "UserName" to ctx.Data on the Go side for them to be accessible with those exact names in template B.

You may want to look into pongo2, a Django-like template for Go (https://github.com/flosch/pongo2)

Your specific use case in pongo2 is documented here: https://github.com/flosch/pongo2/blob/master/template_tests/includes.tpl

huangapple
  • 本文由 发表于 2015年8月4日 12:42:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/31800838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定