kuzicala
kuzicala

Reputation: 25

How to include file which in different folder in go templates

For example there is test.tpl in folder A:

{{define "test"}} hello I am test {{end}}

another index.tpl in folder B:

{{template "A/test"}} or {{template "test"}}

Both do not work.

Upvotes: 0

Views: 2496

Answers (1)

user9455968
user9455968

Reputation:

Use template.ParseFiles and to parse all templates. Use different names for each. This directory layout

.
├── A
│   └── index-A.tpl
├── B
│   └── index-B.tpl
└── main.go

With A/index-A.tpl containing

A

and B/index-B.tpl containing

B1
{{template "index-A.tpl"}}
B2

used by this code

package main

import (
        "os"
        "text/template"
)

func main() {
        t, err := template.ParseFiles("B/index-B.tpl", "A/index-A.tpl")
        if err != nil {
                panic(err)
        }
        err = t.Execute(os.Stdout, nil)
        if err != nil {
                panic(err)
        }
}

will produce this output:

B1
A    
B2

Note that both templates are named in templateParseFiles and that B/index-B.tpl references index-a.tpl by name without the path.

Upvotes: 1

Related Questions