62

I’m using AngularJS as the front-end JS library, with Go templates within Revel framework to to generate the markup on the back-end.

But both Go and Angular use {{ and }} for delimiters in their templates. How can I escape them in Go to pass them to AngularJS?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Coder1
  • 13,139
  • 15
  • 59
  • 89

4 Answers4

109
{{"{{"}}
{{"}}"}}

produces

{{
}}
Mostafa
  • 26,886
  • 10
  • 57
  • 52
  • 1
    @Julien Yeah, because the GoLang templater is _very_ strict and escapes the characters for you. You'll have to jump through a couple hoops to get it to accept them as raw, safe characters. – Wes Alvaro Oct 24 '17 at 07:03
  • 2
    @WesAlvaro Using `html/template` is expected to have the url encoded result. Change the `html/template` to `text/template` works, please refer to http://go-vim.appspot.com/p/Cj_n9mvnxg – willisc Nov 22 '19 at 17:27
  • @ChouW Not quite. That's not what I was demonstrating. The [src] attribute of the is treated special and gets its contents encoded. The answer isn't to switch to a different template type, that would cause other issues. – Wes Alvaro Dec 02 '19 at 04:16
  • @WesAlvaro I got it. You want to heads-up that we should take care when we are handling HTML tags, right? – willisc Dec 04 '19 at 08:37
64

A simple workaround would be using

{{`{{Your.Angular.Data}}`}}
JSNoob
  • 1,477
  • 2
  • 18
  • 31
  • 2
    This doesn't work if your template data is a Go string. In other words, `var templateData = \`{{\`{{Angular.Data}}\`}}\`` is invalid Go (in that trivial example, you don't need to use tick-strings, but in real world examples this is useful). – weberc2 Jun 08 '22 at 19:57
34

I don't know how to escape it, but you could choose a different delimiter instead using Delims:

func (t *Template) Delims(left, right string) *Template

According to the mailing list, this is probably the best option. The argument was that if you escape it, your templates will be hard to read, so it would probably be better anyway to change the delimiter instead of trying to hack around it.

beatgammit
  • 19,817
  • 19
  • 86
  • 129
  • 5
    Worth mentioning, this change [can be done on the Angular](http://stackoverflow.com/q/12923521/1348195) side too. – Benjamin Gruenbaum Jul 14 '13 at 17:48
  • 6
    @tjameson Thanks, that also helped me find the revel framework supports it as a config. To change it to `[[` and `]]`, it would be dfined in app.conf as `template.delimiters = "[[ ]]"`. – Coder1 Jul 14 '13 at 18:23
  • @BenjaminGruenbaum Great info, I wasn't aware, but now that I think about it, hardly surprised they already have a solution for that. Thanks. – Coder1 Jul 14 '13 at 18:24
-4

In Revel, there is a way to handle it:

In /conf/app.conf, add this line:

template.delimiters="[[ ]]"

It will use [[]] instead of using default {{}}, you can also use:

template.delimiters="{{{ }}}"

So, for revel, it uses {{{ }}}, for angularJS, it uses {{ }}

Timothy Ye
  • 23
  • 3