doufei0933 2017-05-10 03:26
浏览 151
已采纳

通过Golang中的模板解析自定义变量

Is it possible for me to set a variable in a template file {{$title := "Login"}} then parse it through to another file included using {{template "header" .}}?

An example of what I'm attempting:

header.tmpl

{{define "header"}}
<title>{{.title}}</title>
{{end}}

login.tmpl

{{define "login"}}
<html>
    <head>
        {{$title := "Login"}}
        {{template "header" .}}
    </head>
    <body>
        Login Body!
    </body>
</html>
{{end}}

How can I parse this custom $title variable I made through to my header template?

  • 写回答

2条回答 默认 最新

  • dongren9739 2017-05-10 09:02
    关注

    As @zzn said, it's not possible to refer to a variable in one template from a different one.

    One way to achieve what you want is to define a template – that will pass through from one template to another.

    header.html {{define "header"}} <title>{{template "title"}}</title> {{end}}

    login.html {{define "title"}}Login{{end}} {{define "login"}} <html> <head> {{template "header" .}} </head> <body> Login Body! </body> </html> {{end}}

    You could also pass through the title as the pipeline when you invoke the "header" template ({{template header $title}} or even {{template header "index"}}), but that will prevent you passing in anything else to that template.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器