dongwenyou4298 2019-02-10 15:44
浏览 75
已采纳

更新嵌套模板Golang

I am trying to change contents dynamically. But the content remains the same. Seems to fetch first match. no matter what the template is. Does not work even with hardcoded file names. The code works as expected but the content cannot be changed.

Main layout

{{define "layout"}}
    <html>
    <body>
        {{ template "content" }}
    </body>
    </html>
{{end}}

Sub template 1

{{ define "content" }}

<h1 style="color: red;">Page 1!</h1>

{{ end }}

Sub template 2

{{ define "content" }}

<h1 style="color: blue;">Page 2!</h1>

{{ end }}

The Go code

package main

import (
    "html/template"
    "net/http"
    "strings"
)

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
}

func main() {
    http.HandleFunc("/", index)
    http.ListenAndServe(":8080", nil)
}

func index(w http.ResponseWriter, r *http.Request) {

    path := strings.Trim(r.URL.Path, "/")
    switch path {
    case "":
        path = ("index.gohtml")
    default:
        path = (path + ".gohtml")
    }

    err := tpl.ExecuteTemplate(w, "layout", path)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}

I have also tried to ParseFiles before Execute with no luck. What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • douqianmin5367 2019-02-11 14:59
    关注

    Adjusting the path after the templates have been parsed is too late, I believe.

    What could work (though I'm not sure is the most elegant solution here) is using the AddParseTree method:

    AddParseTree adds parse tree for template with given name and associates it with t. If the template does not already exist, it will create a new one. If the template does exist, it will be replaced.

    Applied to your case, based on the condition you would Parse the relevant template file (sub template 1 or 2), and then add it with AddParseTree to tpl, before you execute it.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog