问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/55035670/literal-braces-in-handlebars-template