Answer the question
In order to leave comments, you need to log in
Go HTML Template: how to display variable values in nested templates?
I use templates in Go nested one inside the other. I use variables in both templates. Values are substituted in the root template, but not in the nested template. What am I doing wrong?
Root template ( main_container.tpl ):
<!DOCTYPE html>
<html>
<head>
<title>{{ .Title}}</title>
</head>
<body>
<header>
<div id="logo"></div>
</header>
<main>
{{template "content"}}
</main>
</body>
</html>
{{define "content"}}
<div class="categories_select">
<ul>
{{range .Categories}}
<li>{{ .Name}}</li>
{{end}}
</ul>
</div>
{{end}}
t, err := template.ParseFiles("templates/main_container.tpl", "templates/index.tpl")
log.Println("Template: ", t.Tree)
if err != nil {
log.Println("Template err: ", err.Error())
} else {
err = t.Execute(w, templates.GetIndexData())
if err != nil {
log.Println("Template execute err: ", err.Error())
}
}
<!DOCTYPE html>
<html>
<head>
<title>Vitima - Главная</title>
</head>
<body>
<header>
<div id="logo"></div>
</header>
<main>
<div class="categories_select">
<ul>
</ul>
</div>
</main>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
You do not pass data to the nested template, you need to do this, for example:
If you want to pass only categories inside, you can do this:
But then you will need to iterate over them in a different way:
{{range .}}
<li>{{ .Name}}</li>
{{end}}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question