Salah Eddine Taouririt
Salah Eddine Taouririt

Reputation: 26465

Defining a top level go template

Suppose that I have tow text files (go templates):

child.tmpl

TEXT1 
Hello {{ . }}

top.tmpl

TEXT2
{{ template "child.tmpl" "argument"}}

the child.tmpl template is nested in top.tmpl

A typical program to parse them will be :

package main

import (
    "os"
    "text/template"
)

func main() {
    t := template.Must(template.ParseFiles("child.tmpl", "top.tmpl")
    t.ExecuteTemplate(os.Stdout, "top.tmpl", nil)
}

Is there any method the pass the template to be embedded in the top-level template as an argument using the {{ . }} notation ? something like {{ template {{.}} "argument" }}

Upvotes: 2

Views: 344

Answers (1)

thwd
thwd

Reputation: 24858

There are two accepted ways to solve your problem:

The first involves writing your own template-inclusion function and registering it as an template.FuncMap with your template through template.Funcs.

The other way is to use {{define xxx}} blocks in your child templates. Then you could have two different files that define the same template:

  • file1.html: {{define body}}...{{end}}
  • file2.html: {{define body}}...{{end}}

Parse the correct file depending on your needs and in your parent template just do {{template body "argument"}}.

In my opinion, the first option is more flexible.

Upvotes: 2

Related Questions