duanjiongzhen2523 2018-12-15 12:16
浏览 98

html / template:“ xxx”是一页的未定义错误,而另一页不是

again I'm stuck. I've been experimenting with Golang using this page as a guide for templates to create a master page. I've managed to get the Go server up with my CSS and JS directories all updated correctly but I am only able to load the index.html page and not the about.html page. Github link here

I have already tried the solutions in here and here but no luck, both the about page and index page are in the same directory and share the same header, footer and navigation bar templates.

I have also tried parsing files manually with template.Must(template.ParseFiles("header.html", ..... and also tried executing with the .html in the name templ.ExecuteTemplate(w, "about.html", &Page{Title: "About TL;DR"}) which does not return an error but instead just loads a blank screen. Any help will be greatly appreciated, thank you in advance!

File directory:

File directory structure

servermain.go

package main

    import (
        "fmt"
        "html/template"
        "log"
        "net/http"
        "os"
        "path/filepath"
        "strings"
    )

    //Page title
    type Page struct {
        Title string
    }

    //------------------------------Global Variables-------------------------------------//
    //Compile templates on start
    var templ = ParseTemplates()

    //ParseTemplates use for multi directory html parsing
    func ParseTemplates() *template.Template {
        t := template.New("Base")
        err := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
            if strings.Contains(path, ".html") {
                _, err = t.ParseFiles(path)
                fmt.Println(path)
                if err != nil {
                    logger.Println(err)
                    fmt.Println(err)
                }
            }

            return err
        })

        if err != nil {
            panic(err)
        }

        return t
    }

    //logging
    var errorlog *os.File
    var logger *log.Logger

    //---------------------------------------Page Handlers----------------------------------//
    //Handler for homepage
    func homepageHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Home")
        err := templ.ExecuteTemplate(w, "index", &Page{Title: "Welcome to TL;DR"})
        if err != nil {
            fmt.Println(err)
            logger.Println(err)
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    }

    //Handler for about page
    func aboutHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Println("About")
        err := templ.ExecuteTemplate(w, "about", &Page{Title: "About TL;DR"})
        if err != nil {
            fmt.Println(err)
            logger.Println(err)
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    }

    //Server log to file
    func init() {
        errorlog, err := os.OpenFile("serverlog.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
        if err != nil {
            fmt.Printf("Error opening file: %v", err)
            os.Exit(1)
        }
        log.SetOutput(errorlog)
        logger = log.New(errorlog, "
TDLR : ", log.Lshortfile|log.LstdFlags)
    }

    func main() {
        //--------------------------------------Routers-------------------------------------//
        http.HandleFunc("/", homepageHandler)
        http.HandleFunc("/index", homepageHandler)
        http.HandleFunc("/about", aboutHandler)

        http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
        //---------------------------------------------------------------------------------//
        //start server
        fmt.Println("Starting server on port 9090")
        logger.Println("Starting server on port 9090")
        logger.Fatal(http.ListenAndServe(":9090", nil))

    }

Error page

Error page

Also I noticed no matter what page I load it will always execute the homepageHandler after executing the aboutHandler as can be seen in the console.

Console result

Edit: Solved 20181215 Improper definition of the about.html template, change to {{define "about"}} solved the problem.

  • 写回答

1条回答 默认 最新

  • douye2488 2018-12-15 13:36
    关注

    I tested your code in my PC, it works OK. If you see a blank screen with about.html ( .html in the name ) it's probably your template's problem.
    Make sure you have below code inside your about.html

    {{.Title}}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊