Literal braces in Handlebars template

若如初见. 提交于 2019-12-11 15:37:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!