dpf25323 2018-02-13 19:06
浏览 4
已采纳

插入模板名称作为类

When creating a Go template, you can give it a name, like in this example, "my_home_template":

var tmplHome = template.Must(template.New("my_home_template").Funcs(funcMap).ParseFiles("templates/base.tmpl", "templates/content_home.tmpl"))

How can I get that template name and use it inside the actual template file?

Ultimately I just want to define a convenient css class, like so:

<body class="my_home_template">
  • 写回答

1条回答 默认 最新

  • dou12754 2018-03-08 13:03
    关注

    Here's a working solution, taking mkopriva's advice:

    When executing a template, pass some custom parameter with dummy data. Here, I just create a "PageHome" parameter to pass to the template, and value is a simple "1", but it could be any value:

    tmplHome.ExecuteTemplate(w, "base", map[string]interface{}{"PageHome": "1", "Data": events, "UserFirstName": &u.FirstName, "UserProfilePic": &u.ProfilePic})
    

    Then, inside the template itself, a simple if statement to check if the parameter exists, and do something accordingly:

    {{ if .PageHome }}
        <body class="PageHome">
    {{ else }}
        <body>
    {{ end }}
    

    All my other template executions don't pass a "PageHome" parameter at all, so the if statement never passes as true for them.

    There's probably a more advanced solution using a functions via a template function map, and having a consistent "PageType":"something" parameter in all template executions, but in the end you still have to define a parameter per template execution and still have to build up if statements in your templates anyways.

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

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作