user2326871
user2326871

Reputation: 239

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

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

Upvotes: 13

Views: 2748

Answers (4)

Steve Coffey
Steve Coffey

Reputation: 21

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

Upvotes: 2

Peter Miehle
Peter Miehle

Reputation: 6070

my adhok solution was:

\barcode{{print "{" .Barcode}}}

Upvotes: 0

Baruch
Baruch

Reputation: 1133

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.

Upvotes: 0

zzzz
zzzz

Reputation: 91303

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.

Upvotes: 16

Related Questions