模板继承在Go中创建了一个空白页面。

huangapple go评论96阅读模式
英文:

Template inheritance creates blank page in go

问题

我正在尝试使用Go创建一个全栈应用程序,但在模板部分遇到了问题。

以下代码在页面静态时是正常的,但当我开始使用继承函数(如{{template}},{{define}}或{{block}})时,返回一个空白页面。

main.go:

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

func main() {
	router := mux.NewRouter()

	router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		fmt.Println("begin")
		files := []string{
			"layout.html",
			"index.html",
		}

		tmpl, err := template.ParseFiles(files...)
		if err != nil {
			http.Error(rw, fmt.Sprintf("failed parsing template files | %s", err.Error()), http.StatusInternalServerError)
			return
		}

		if err := tmpl.Execute(rw, nil); err != nil {
			http.Error(rw, fmt.Sprintf("failed rendering template | %s", err.Error()), http.StatusInternalServerError)
			return
		}
	}).Methods("GET")

	if err := http.ListenAndServe(fmt.Sprintf(":3000"), router); err != nil {
		log.Fatalf("failed starting server | %s", err.Error())
	}
}

layout.html

{{define "base"}}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
        <!-- bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <title></title>
    </head>
    <body>
        <main>
            {{template "main" .}}
        </main>
        <!-- JQuery, Popper.js, Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    </body>
</html>

{{end}}

index.html

{{template "base" .}}

{{ define "main" }}
    <h2>hello</h2>
    <p>test</p>
{{ end }}

我已经完全复制了示例,但它仍然无法工作。我漏掉了什么?

英文:

I'm trying to create a full stack app in go but I'm having trouble with the templating part.

The following code is fine as long as the page is static, but returns a blank page when i start using inheritance functions such as {{template}}, {{define}} or {{block}}.

main.go :

package main

import (
	&quot;fmt&quot;
	&quot;html/template&quot;
	&quot;log&quot;
	&quot;net/http&quot;

	&quot;github.com/gorilla/mux&quot;
)

func main() {
	router := mux.NewRouter()

	router.HandleFunc(&quot;/&quot;, func(rw http.ResponseWriter, r *http.Request) {
		fmt.Println(&quot;begin&quot;)
		files := []string{
			&quot;layout.html&quot;,
			&quot;index.html&quot;,
		}

		tmpl, err := template.ParseFiles(files...)
		if err != nil {
			http.Error(rw, fmt.Sprintf(&quot;failed parsing template files | %s&quot;, err.Error()), http.StatusInternalServerError)
			return
		}

		if err := tmpl.Execute(rw, nil); err != nil {
			http.Error(rw, fmt.Sprintf(&quot;failed rendering template | %s&quot;, err.Error()), http.StatusInternalServerError)
			return
		}
	}).Methods(&quot;GET&quot;)

	if err := http.ListenAndServe(fmt.Sprintf(&quot;:3000&quot;), router); err != nil {
		log.Fatalf(&quot;failed starting server | %s&quot;, err.Error())
	}
}

layout.html

{{define &quot;base&quot;}}
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
    &lt;head&gt;
        &lt;meta charset=&quot;UTF-8&quot;&gt;
        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0, shrink-to-fit=no&quot;&gt;
        &lt;!-- bootstrap CSS --&gt;
        &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css&quot; integrity=&quot;sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T&quot; crossorigin=&quot;anonymous&quot;&gt;
        &lt;title&gt;&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;main&gt;
            {{template &quot;main&quot; .}}
        &lt;/main&gt;
        &lt;!-- JQuery, Popper.js, Bootstrap JS --&gt;
        &lt;script src=&quot;https://code.jquery.com/jquery-3.3.1.slim.min.js&quot; integrity=&quot;sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js&quot; integrity=&quot;sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js&quot; integrity=&quot;sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;

{{end}}

index.html

{{template &quot;base&quot; .}}

{{ define &quot;main&quot; }}
    &lt;h2&gt;hello&lt;/h2&gt;
    &lt;p&gt;test&lt;/p&gt;
{{ end }}

I've literally copied the examples and it still doesn't work. What am I missing ?

答案1

得分: 1

ParseFiles 返回参数列表中第一个文件的模板。文件的模板是 {{define}}/{{end}} 块之外的内容。

列表中的第一个文件 layout.html,在 {{define}}/{{end}} 块之外只有空白内容。

你想要的是文件 index.html 中的模板。交换文件的顺序以解决这个问题。

files := []string{
    "index.html",
    "layout.html",
}
英文:

ParseFiles returns the template for the first file in the argument list. The template for a file is the content outside of {{define}}/{{end}} blocks.

The first file in the list, layout.html, has nothing but whitespace outside of the {{define}}/{{end}} block.

You want the template in the file index.html. Swap the order of the files to fix the problem.

    files := []string{
&quot;index.html&quot;,
&quot;layout.html&quot;,
}

huangapple
  • 本文由 发表于 2022年2月20日 15:06:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/71192060.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定