1

I'm having difficulties including braces { } in a Handlebars template so that it didn't interfere with Handlebars syntax.

Specifically, I want to have a template like this:

{{{sometag}}}

Except that I want the first and the last braces to be rendered literally, rather than be a part of Handlebar's "non-escaped expression" syntax.

For now, the shortest portable syntax I could come up with is {{#with "{"}}{{.}}{{/with}}, so that the template that I want would look like:

{{#with "{"}}{{.}}{{/with}}{{sometag}}{{#with "}"}}{{.}}{{/with}}

I could use HTML entities (like https://stackoverflow.com/a/16278085/3088208 suggests), or insert an HTML comment after the initial { and before the final }, but these solutions, while practical, depend on HTML which makes them limited.

P. S. Found a duplicate question: Escaping curly brackets standing next to expression in handlebars

pvgoran
  • 442
  • 3
  • 14

3 Answers3

2

For anyone who lands here in the future, this solution worked for me Render double curly-brackets inside handlebars partial

TL;DR Add a \ to your value eg \{{{whatever}}} will render {{{whatever}}}

adam_th
  • 397
  • 3
  • 11
1

Have you tried { {{~sometag~}} }? As I understand the "specification" and your question, it should do what you want: The outer braces are single and will be quoted verbatim, but the adjacent white space should be removed because of the tildes.

  • Nice and short, thank you! And it works perfectly with Java Handlebars implementation that I use (even though I already don't remember the use case that I had for this). Marking as answer. – pvgoran Aug 10 '23 at 05:38
0

I was also searching for this solution and couldn't find anything. So I've created helper

Handlebars.registerHelper('bracket', function(num, options = num) {
 const i = Number.isInteger(num) ? num : 1;
 const open = '{'.repeat(i);
 const close = '}'.repeat(i);
 return `${open}${options.fn(this)}${close}`;
});

You can use it like

{{#bracket 2}}styles.{{name}}{{/bracket}}

it will give

{{styles.Name}}

If number of brackets was not specified it will be one.

Talgat Saribayev
  • 1,898
  • 11
  • 19
  • Thanks for your suggestion, but using a helper adds a dependency that I want to avoid if I can. (If I wanted to go with a helper solution, I would define an inline helper to be used like this: `{{literal '{'}}{{sometag}}{{literal '}'}}` – pvgoran Mar 15 '19 at 05:10