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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?