admin管理员组文章数量:1332395
I am using express-handlebars
and have the following minimal template:
<!DOCTYPE html>
<html>
<body>
{{#if page === 'help'}}YAAAY{{/if}}
</body>
</html>
This fails to parse with:
Error: C:\Users\mike\myapp\views\error.hbs: Parse error on line 6:
...ody> {{#if page === 'help'}}YAAAY{{/i
---------------------^
I understand handlebars isn't expecting an ===
, but isn't that the point of if
?
How can I use an if
statement in handlebars?
I am using express-handlebars
and have the following minimal template:
<!DOCTYPE html>
<html>
<body>
{{#if page === 'help'}}YAAAY{{/if}}
</body>
</html>
This fails to parse with:
Error: C:\Users\mike\myapp\views\error.hbs: Parse error on line 6:
...ody> {{#if page === 'help'}}YAAAY{{/i
---------------------^
I understand handlebars isn't expecting an ===
, but isn't that the point of if
?
How can I use an if
statement in handlebars?
-
Try
==
instead. – Code-Apprentice Commented Aug 20, 2018 at 15:17 - 1 Handlerbars have if only for checking if value is true or false it's not if like in javascript for this you will need to created your own helper. – jcubic Commented Aug 20, 2018 at 15:19
- 3 Wow: stackoverflow./a/16315366/1225328. I'm curious to know the reasoning behind this "no boolean operator" choice they made to be honest. – sp00m Commented Aug 20, 2018 at 15:20
- @sp00m care to post another answer with this link or edit my answer? Think it's very helpful in this context ;-) – Lyubomir Commented Aug 20, 2018 at 15:24
-
1
@sp00m There's an
if
, it's already not logic-less. The point is to minimize the amount of putation in views, as it's almost always easier to test that logic outside of templates (and that logic has a tendency to accrete, making it even harder). – Dave Newton Commented Aug 20, 2018 at 15:57
2 Answers
Reset to default 6Handlebar's if-helper
only accepts a boolean as an argument. You have two options:
Use the existing handler
Pass the result from page === 'help'
as a variable in the template and do something like:
{{#if isPageHelp}}
<h1> Help! </h1>
{{/if}}
Make your own handler
You can implement the ===
operator with your own handler. Thanks @sp00m.
Try this helpers
const Handlebars = require('handlebars');
Handlebars.registerHelper('ifCond', function (v1,v2,options) {
if (v1 == v2)
return options.fn(this);
else
return options.inverse(this);
});
Handlebars.registerHelper('exCond', function (v1,v2,options) {
if (v1 != v2)
return options.fn(this);
else
return options.inverse(this);
});
本文标签: javascriptBasic 39if39 statements do not work in handlebars JSStack Overflow
版权声明:本文标题:javascript - Basic 'if' statements do not work in handlebars JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742283537a2446528.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论