Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang html/templates : ParseFiles with custom Delims

Using templates with delimiters works fine when using template.New("...").Delims("[[", "]]").Parse() However, I cannot figure out how to get to the same result with template.ParseFiles()

tmpl, err := template.ParseFiles("base.tmpl", "homepage/inner.tmpl")
if err != nil { panic(err) }
tmpl.Delims("[[", "]]")
p := new(Page) 
err = tmpl.Execute(os.Stdout, p)
if err != nil { panic(err) }

I have no errors, but the Delimiters are not changed.

tmpl, err := template.ParseFiles("base.tmpl", "homepage/inner.tmpl")
t := tmpl.Lookup("base.tmpl").Delims("[[", "]]")
p := new(Page) 
err = t.Execute(os.Stdout, p)
if err != nil { panic(err) }

This leads to the same result.

In case this is relevant, my need is to embed a small angular app in a particular page of my site.

Also, I have a base template with a common HTML structure that I combine with a page-specific template with ParseFiles(), leading to this layout :

/templates/base.tmpl
/templates/homepage/inner.tmpl
/templates/otherpage/inner.tmpl

Is this possible at all ? If so, what am I doing wrong ?

like image 215
Jérémy Avatar asked Mar 18 '23 19:03

Jérémy


1 Answers

Create a dummy template, set the delimiters and then parse the files:

 tmpl, err := template.New("").Delims("[[", "]]").ParseFiles("base.tmpl", "homepage/inner.tmpl")

This aspect of the API is quirky and not very obvious. The API made more sense in the early days when the template package had the additional Set type

like image 83
Mixcels Avatar answered Apr 26 '23 07:04

Mixcels