Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape curly brackets in templates

Tags:

go

How do I escape curly brackets in golangs template system?
Assume I want to print {{Hello World}}:

var buf bytes.Buffer
// tpl := template.Must(template.New("").Parse(`{{ print "{{Hello World}}"}}`)) // this is working
tpl := template.Must(template.New("").Parse(`\{\{Hello World\}\}`)) // this is not
if err := tpl.Execute(&buf, nil); err != nil {
    panic(err)
}
if buf.String() != "{{Hello World}}" {
    panic("Unexpected")
}

go playground

like image 940
Eun Avatar asked Jul 13 '18 13:07

Eun


People also ask

Do curly braces need to be escaped in regex?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.

What are the curly brackets {{ }} used for?

In writing, curly brackets or braces are used to indicate that certain words and/or sentences should be looked at as a group. Here is an example: Hello, please pick your pizza toppings {chicken, tomatoes, bacon, sausage, onion, pepper, olives} and then follow me.

How do you escape curly braces in Jira?

After entering the curly brace and the macro menu pops up, press the ESC key and the menu will go away leaving the curly brace there. However, if you put in a closing brace it will still try to convert it to a wiki markup macro, so copy/paste will be your best bet in that case.

What is the purpose of {} squiggly braces in Java?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.


1 Answers

You can use a raw string constant.

tpl := template.Must(template.New("").Parse("{{`{{Hello World}}`}}"))

https://play.golang.org/p/FmPo6uMUBp8

like image 125
Massimo Zerbini Avatar answered Oct 27 '22 07:10

Massimo Zerbini