staffID
@staffID

Где ошибка templates?

Недавно начала разбираться с Go.
И вот сейчас разбираюсь с шаблонами.

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>


Ожидаемый результат:
<!DOCTYPE html>
<html>
<head>
    <title>text</title>
</head>
<body>
    text
</body>
</html>

Результат:
""

Где ошибка?
  • Вопрос задан
  • 253 просмотра
Решения вопроса 2
uvelichitel
@uvelichitel Куратор тега Go
habrahabr.ru/users/uvelichitel
Чтобы template исполнялся его нужно распарсить, определить и именовать.
Недостаточно указать путь к файлу
{{ template "templates/header.html" . }} //<-вот здесь ошибка

А нужно примерно так
t, err := template.ParseFiles( "templates/content.html" , "templates/header.html", "templates/footer.html")

файлы
content.html:
{{ template "header" . }}
    text
{{ template "footer" . }}

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

footer.html:
{{define "footer"}}
</body>
</html>
{{end}}
Ответ написан
Комментировать
@malbaron
Напишите вместо

t.Execute( res, nil )

так

if err:= t.Execute( res, nil ); err != nil {
   log.Printf( err )
}


и все поймете
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы