如何在Handlebars中设置非(!)判断?附JSON与代码场景
Hey there! I see you're trying to adjust your Handlebars template to only render the responsive background image styles when bg-image.unique is not present/empty. Handlebars doesn't have a native ! operator for if blocks, but we've got two straightforward ways to handle this:
1. Use Handlebars' Built-in {{unless}} Helper
The simplest solution is to use Handlebars' built-in unless helper—it's essentially the inverse of if. It will execute the block content only when the given expression evaluates to false, empty, null, or undefined (exactly what you need for !bg-image.unique).
Here's how to modify your existing Handlebars code:
{{#unless bg-image.unique}} <style> @media screen and (max-width:642px) { .masthead { background-image: url({{bg-image.sm}}); } } @media screen and (min-width:643px) { .masthead { background-image: url({{bg-image.md}}); } } </style> {{/unless}}
How this works:
- If
bg-image.uniqueis an empty string (like in your JSON),null,undefined, orfalse, theunlessblock will render your responsive styles. - If
bg-image.uniquehas a value, the block will be skipped entirely.
2. Create a Custom not Helper (For More Flexibility)
If you need more control over negation (or want to use !-like syntax explicitly), you can register a custom not helper with Handlebars.
First, register the helper in your JavaScript code:
Handlebars.registerHelper('not', function(value) { return !value; });
Then, use it in your template with Handlebars' subexpression syntax (parentheses):
{{#if (not bg-image.unique)}} <style> @media screen and (max-width:642px) { .masthead { background-image: url({{bg-image.sm}}); } } @media screen and (min-width:643px) { .masthead { background-image: url({{bg-image.md}}); } } </style> {{/if}}
This achieves the exact same logic as the unless approach, but lets you use a more explicit negation syntax if that's what you prefer.
Quick Note on Your JSON Structure
Since your bg-image object has empty strings for sm and md, make sure those values get populated correctly before rendering the template—otherwise, you'll end up with url() which might cause unexpected behavior in browsers.
内容的提问来源于stack exchange,提问作者Reacting

