英文:
How to perform string contains check in handlebarsjs
问题
如何在Handlebars.js中在if块内执行字符串包含检查
{{ if loop_var.imageUri }}
# 如果 loop_var.imageUri 包含 foo
<img width="50" height="50" src="{{loop_var.imageUri}}"/>
# 否则
<img width="150" height="150" src="{{loop_var.imageUri}}"/>
# 结束
{{ else }}
{{ end }}
英文:
How to perform string contains check in handlebarsjs within the if block
\{{ if loop_var.imageUri }}
# if loop_var.imageUri contains foo
<img width="50" height="50" src="{{loop_var.imageUri}}"/>
# else
<img width="150" height="150" src="{{loop_var.imageUri}}"/>
# end
\{{ else }}
\{{ end }}
答案1
得分: 1
Handlebars没有提供用于在两个字符串上执行包含比较的帮助器,但你可以轻松创建自己的帮助器。它需要是一个块帮助器,这样你就可以为不匹配的情况添加{{else}}
分支。
const template = Handlebars.compile(`
{{#if loop_var.imageUri}}
{{#ifContains loop_var.imageUri 'foo'}}
<img width="50" height="50" src="{{loop_var.imageUri}}"/>
{{else}}
<img width="150" height="150" src="{{loop_var.imageUri}}"/>
{{/ifContains}}
{{/if}}
`);
Handlebars.registerHelper('ifContains', function (source, subString, options) {
if (source.indexOf(subString) > -1) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
const data = {
loop_var: {
imageUri: '/my/foo/image/'
}
};
const output = template(data);
document.body.innerHTML = output;
英文:
Handlebars has no helper to do a contains comparison on two strings, but you can easily create your own. It would need to be a Block Helper so that you can add the {{else}}
branch for cases of non-matches.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const template = Handlebars.compile(`
{{#if loop_var.imageUri}}
{{#ifContains loop_var.imageUri 'foo'}}
<img width="50" height="50" src="{{loop_var.imageUri}}"/>
{{else}}
<img width="150" height="150" src="{{loop_var.imageUri}}"/>
{{/ifContains}}
{{/if}}
`);
Handlebars.registerHelper('ifContains', function (source, subString, options) {
if (source.indexOf(subString) > -1) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
const data = {
loop_var: {
imageUri: '/my/foo/image/'
}
};
const output = template(data);
document.body.innerHTML = output;
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论