GO语言总是在html中打印错误的条件部分

问题描述 投票:0回答:1

关于问题

我正在使用 Go 语言并尝试将 bool 变量值从函数传递到 html。请检查函数

articlesHandler
,其中
IsLoggedIn
值已初始化为true,并且它还成功打印了同一函数中存在的true条件部分。

现在,请检查 html 块,有两个 if 条件,我的问题是它总是在 html 中打印 false 部分而不是 true 部分。

你能推荐一些东西吗?

另一个问题

没有这样的模板“anonymous-nav.html”

main.go代码

var templates *template.Template
var pageData pageProps

type pageProps struct {
    IsLoggedIn bool
}

func articlesHandler(w http.ResponseWriter, r *http.Request) {
    pageData.IsLoggedIn = true
    templates = template.Must(template.ParseGlob("templates/article/*.html"))
    if pageData.IsLoggedIn == true {
        templates.ParseFiles("templates/authenticated-nav.html")
        fmt.Println("err", "authenticated")
    } else {
        templates.ParseFiles("templates/anonymous-nav.html")
        fmt.Println("err", "anonymous")
    }
    err := templates.ExecuteTemplate(w, "article.html", pageData)
    if err != nil {
        fmt.Println("err", err)
    }
}
func handler(w http.ResponseWriter, r *http.Request) {
    articlesHandler(w, r)       
}

func main() {
    http.HandleFunc("/", handler)
    pageData = pageProps{
        IsLoggedIn: false,
    }
    http.ListenAndServe(":8080", nil)
}

HTML代码

{{ if .IsLoggedIn }}
    {{ template "authenticated-nav.html" . }}
{{end}}

{{ if not .IsLoggedIn }}
    {{ template "anonymous-nav.html" . }}
{{end}}
go go-templates
1个回答
1
投票

我的问题是它总是在 html 中打印错误部分而不是真实部分

我猜你这么说是因为你看到了这个错误消息:

html/template:article.html:6:16:没有这样的模板“anonymous-nav.html”

但是这个错误信息并不意味着

.IsLoggedIn
中的
{{ if not .IsLoggedIn }}
false
html/template
包调用escapeTemplate遍历所有模板,如果没有找到任何一个则报告错误(无论模板是否会被渲染)。

通过以下演示很容易观察到这种行为:

package main

import (
    "fmt"
    "html/template"
    "os"
)

func main() {
    tmpl, err := template.New("test").Parse(`
{{ if false }}
    {{ template "authenticated-nav.html" . }}
{{end}}`)
    if err != nil {
        panic(err)
    }
    err = tmpl.Execute(os.Stdout, nil)
    fmt.Printf("%v\n", err)
    // Output: html/template:test:3:16: no such template "authenticated-nav.html"
}

请注意,

text/template
包没有此行为。

对于您的用例,我认为最好将

article.html
模板编写为:

{{ template "nav" . }}

并修改

anonymous-nav.html
authenticated-nav.html
来定义同名模板
nav
:

{{define "nav"}}
...
{{end}}
© www.soinside.com 2019 - 2024. All rights reserved.