没有第三方导入的 Golang 中的 html 渲染器

我正在自学 go 并且我已经开始尝试使用 go 作为后端。


我有以下呈现 HTML 页面的代码,但我正在寻找一种不依赖第三方导入的解决方案,以便更好地掌握正在发生的事情和需要做的事情。


package main


import (

    "log"

    "net/http"


    "github.com/thedevsaddam/renderer"

)


var rnd *renderer.Render


func init() {

    opts := renderer.Options{

        ParseGlobPattern: "./pages/*.gohtml",

    }

    rnd = renderer.New(opts)

}


func main() {

    mux := http.NewServeMux()

    mux.HandleFunc("/", home)

    mux.HandleFunc("/about", about)

    port := ":9000"

    log.Println("Listening on port ", port)

    http.ListenAndServe(port, mux)

}


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

    rnd.HTML(w, http.StatusOK, "home", nil)

}


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

    rnd.HTML(w, http.StatusOK, "about", nil)

}


GOHTML 文件是:


{{ define "home"}}

<!DOCTYPE html>

<html>

<head>

  <title>Home</title>

</head>

<body>

  <h1>HOME</h1>

  <ul>

    <li><a href="/">Home</a></li>

    <li><a href="/about">About</a></li>

  </ul>

</body>

</html>

{{ end }}

{{ define "about" }}

<!DOCTYPE html>

<html>

<head>

  <title>About</title>

</head>

<body>

  <h1>ABOUT</h1>

  <ul>

    <li><a href="/">Home</a></li>

    <li><a href="/about">About</a></li>

  </ul>

</body>

</html>

{{ end }}

任何帮助是极大的赞赏


阿晨1998
浏览 124回答 1
1回答

慕妹3146593

使用标准库中的html/template包。您使用的渲染器只是围绕它的一个薄包装器。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go