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" .}}

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

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题