我有一个handlebar表达式,它为我提供了一个动态字符串。我想删除字母之间的空格,并将其用作div id。我知道我可以使用JS做到这一点。但是有没有办法在handlebar模板中做到这一点呢?
{{name}}为我提供了“abc xyz”,而我想要“abcxyz”字符串。
发布于 2018-09-30 00:45:22
您可以自己注册一个helper,并在模板中使用它将字符串中的空格替换为空。
Handlebars.js has a function registerHelper(String, Function)
(如您所见)接受一个字符串(帮助器的名称)和一个返回帮助器结果的函数。
例如,如果我们想要一个帮助器函数,将给定字符串中的"Facebook“替换为"Google”,您可以这样做。
Handlebars.registerHelper('replace', function(string) {
return string.replace('Facebook', 'Google');
});
在模板中,我们像调用{{replace "Hello, Facebook!"}}
一样调用它,它将返回Hello, Google!
。
在多用途函数的情况下(在这种情况下,它显然应该是,而不是我给出的例子),您需要传递字符串来调用替换,要替换的字符串以及应该替换的内容。
Handlebars.registerHelper('replace', function(string, search, replace) {
return string.replace(search, replace);
});
与我们之前使用{{replace "Hello, Facebook!" "Facebook" "Google"}}
在模板中调用它的方式相同。
发布于 2019-12-19 18:28:37
如果您想避免编写自己的帮助器。您可以使用以下模块:https://github.com/helpers/handlebars-helpers
只需安装它
npm install --save handlebars-helpers
现在可以开始了,您可以使用以下帮助程序来解决您的问题:
{{replace name " " ""}}
下面是另一个用法示例:
{{replace "a b a b a b" "a" "z"}}
<!-- results in: 'z b z b z b' -->
https://stackoverflow.com/questions/52570039
复制相似问题