Cover Image for Go template delimiters conflict

Go template delimiters conflict

Currently, I'm working on a project where I need to render LaTex documents using Golang template system. Tex language uses curly braces a lot. For example:

\begin{document}
\textbf{This is bold text}
\vspace{2cm}
\end{document}

By default, Go template system also uses curly braces for defining the placeholders where variables will be rendered and functions will be executed, for example:

Hello, {{ .Name }}!

or

{{if .User.HasPermission "feature-a"}}
  <h1>This is the feature A</h1>
{{end}}

For my project, I was rendering LaTex templates using Golang template system and I was having some troubles. Consider this template:

\textbf{ {{ .Name }} }

When I try to render it using Golang:

tmpl, _ := template.New("latex").Parse(string(content))
tmpl.Execute(witer, templateData)

I get an error:

unexpected "{"

And this is because, as you see in the template, there are 3 consecutive curly braces, and that's a Go template syntax error.

After struggling a bit, I discovered there is a way to change the default Go template delimiters ({{ and }}).

This is the resulting code:

tmpl, _ := template.New("latex").
  Delims("[[", "]]").
  Parse(string(content))
tmpl.Execute(witer, templateData)

As simple as that.


More posts...