M
M
ML2017-02-02 22:25:37
go
ML, 2017-02-02 22:25:37

Where is the templates error?

I recently started learning about Go.
And now I'm dealing with templates.
go:

package main

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

func hello( res http.ResponseWriter, req *http.Request ) {
    res.Header().Set(
        "Content-Type",
        "text/html",
    )
    
    
    t, err := template.ParseFiles( "templates/content.html" )
    if err != nil {
        log.Println( err );
    }
    t.Execute( res, nil )
}

func main() {
    http.HandleFunc( "/", hello )
    http.ListenAndServe(":60", nil )
}

content.html:
{{ template "templates/header.html" . }}
    text
{{ template "templates/footer.html" . }}

header.html:
<!DOCTYPE html>
<html>
<head>
<title>text</title>
</head>
<body>

footer.html:
</body>
</html>

Expected Result:
<!DOCTYPE html>
<html>
<head>
    <title>text</title>
</head>
<body>
    text
</body>
</html>

Result:
""
Where is the error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2017-02-02
@staffID

In order for a template to be executed, it needs to be parsed, defined, and named.
It is not enough to specify the path to the file

{{ template "templates/header.html" . }} //<-вот здесь ошибка

And you need something like this
content.html files :
{{ template "header" . }}
    text
{{ template "footer" . }}

{{define "header"}}
<!DOCTYPE html>
<html>
<head>
<title>text</title>
</head>
<body>
{{end}}

{{define "footer"}}
</body>
</html>
{{end}}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question