A
A
Anton2017-11-17 16:42:47
go
Anton, 2017-11-17 16:42:47

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>

Nested template ( index.tpl ):
{{define "content"}}
<div class="categories_select">
  <ul>
    {{range .Categories}}
      <li>{{ .Name}}</li>
    {{end}}
  </ul>
</div>
{{end}}

Part of the code that parses and renders the template:
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())
      }
    }

Result:
<!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>

It can be seen that the value for {{ .Title}} was substituted. And the value for {{ .Name}} in the nested template was not substituted. Although, when all this was in one template, it worked like clockwork.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-11-17
@lanzert

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 question

Ask a Question

731 491 924 answers to any question