登录
首页 >  Golang >  Go问答

GO语言在html中经常输出错误情况部分

来源:stackoverflow

时间:2024-02-07 16:33:23 133浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《GO语言在html中经常输出错误情况部分》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

关于问题

我正在使用 go 语言并尝试将 bool 变量值从函数传递到 html。请检查函数articleshandler,其中isloggedin值已初始化为true,并且它还成功打印了同一函数中存在的true条件部分。

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

你能提出一些建议吗?

另一个问题

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

ma​​in.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}}

正确答案


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

但此错误消息并不意味着 {{ if not .isloggedin }} 中的 .isloggedinfalsehtml/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.htmlauthenticated-nav.html以定义同名nav的模板:

{{define "nav"}}
...
{{end}}

以上就是《GO语言在html中经常输出错误情况部分》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>