把手模板中的文字括号 [英] Literal braces in Handlebars template
问题描述
我在将Handlebars模板中的花括号{
}
包括在内时遇到了麻烦,以免干扰Handlebars语法.
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}}}
除了我希望第一个括号和最后一个括号大体上是文字显示的,而不是Handlebar的非转义表达式"语法的一部分.
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.
目前,我能想到的最短的可移植语法是{{#with "{"}}{{.}}{{/with}}
,这样我想要的模板看起来像这样:
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}}
我可以使用HTML实体(例如 https://stackoverflow.com/a/16278085/3088208 建议),或在最初的{
之后和最后的}
之前插入HTML注释,但是这些解决方案虽然可行,但取决于HTML,因此受到限制.
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.发现一个重复的问题:在句柄中的表达式旁边转义大括号
P. S. Found a duplicate question: Escaping curly brackets standing next to expression in handlebars
推荐答案
我也在寻找该解决方案,但找不到任何东西.所以我创建了助手
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}`;
});
您可以像使用它
{{#bracket 2}}styles.{{name}}{{/bracket}}
它将给予
{{styles.Name}}
如果未指定方括号数,则为1.
If number of brackets was not specified it will be one.
这篇关于把手模板中的文字括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!