How to execute a Golang template when "{" or "}" are in the static part of the template?
Asked Answered
G

4

13

My Problem is that, I want to build a letter generator, which first builds a latex-file from user input, and then compiles this via latex to PDF.

The template contains multiple lines like this:

\setkomavar{signature}{{{.Name}}}

The latex part is \setkomavar{signature}{}, and the template part from go is {{.Name}}.

When I try to load the template, it throws this error:

panic: template: letter.tmpl:72: unexpected "}" in command

Is there a trick to help the parser handling such a situation?

Thanks in advance,

Tino

Grin answered 23/5, 2013 at 7:3 Comment(0)
S
16

Use Template.Delims to set the delimiters to some non conflicting text. {{ and }} are just the default values, this method allows to select other delimiters.

Alternative method: In you template, where you want latex's { and }, you can insert some safe text instead, like say #( and )# and then make a "global" replacement on the output from the template. Yet setting delimiters is far easier IMO and quite probably more performant, if that matters.

Systematize answered 23/5, 2013 at 7:13 Comment(0)
L
2

A better solution is actually to just use the built in whitespace operators, like:

\setkomavar{signature}{ {{- .Name -}} }

The - at the beginning and end will remove whitespace between that token and the next non-template token.

Hope that helps, see the docs for more detail

Leguminous answered 23/2, 2017 at 0:13 Comment(1)
made my day! was working with a system where I can't change the delimiter.Primo
S
0

I was previously doing this by creating the template function:

func texArg(s interface{}) string {
    return fmt.Sprintf("{%v}", s)
}

which I registered as arg using template.Funcs. Then in my template I had:

\textbf{{.Name | arg}}

I think @zzzz's answer above is better as this falls apart when you need to nest it, but I thought I'd leave this here for an alternative approach.

Selfemployed answered 15/10, 2015 at 15:5 Comment(0)
P
0

my adhok solution was:

\barcode{{print "{" .Barcode}}}
Pecos answered 19/9, 2016 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.