douzhao4071 2018-04-01 23:35
浏览 88
已采纳

解析带有数据的多个模板

How do i pass the data to the right template?

I have the following templates and want to parse them

layout.html:

<!DOCTYPE html>

<html>
    <head>
    ...
    </head>
    <body>
        <header>
        ...
        </header>
        <main>
            {{template "main"}}
        </main>
    </body>
</html>

list.html:

{{define "main"}}
{{range $index, $element := . }}    
    <div>
        <a href=#>{{ $element.Data1 }}</a>
        <p>{{ $element.Data2 }}</p>
        <p>{{ $element.Data3 }}</p>
    </div>
{{end}}
{{end}}

When i use this in the handler func only the "main" template is executed and i dont get the layout.

t, err := template.ParseFiles(layoutPath, templatePath)

t.ExecuteTemplate(w, "main", Data)

And with this i dont have the Data in the list template and so cant display the list.

t, err := template.ParseFiles(layoutPath, templatePath)

t.ExecuteTemplate(w, Data)

So how do i execute this properly?

  • 写回答

1条回答 默认 最新

  • dt2002 2018-04-02 09:11
    关注

    From the docs:

    {{template "name" pipeline}} The template with the specified name is executed with dot set to the value of the pipeline.

    This means that to pass data from the layout.html template to the list.html template you need to pass the data as the second argument of the template action.

    E.g. {{template "main" .}}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办