Handlebars - Best Practices
Table of Contents
When adding Handlebars, there are some Best Practices to keep in mind:
- Always provide fallbacks:
- Use
defaultororhelpers to ensure graceful degradation when data is missing.- Hello {{or [First-Name] "Valued Customer"}}!
- Use
- Wrap complex variables:
- Any variable name with special characters (hyphens, colons, spaces) must be wrapped in square brackets:
- {{[First-Name]}} Correct (has hyphen)
- {{[todaysdate:Ymd]}} Correct (has colon)
- {{[subscriber-timezone]}} Correct (has hypen)
- {{First-Name}} Incorrect (should be wrapped in square brackets)
- Any variable name with special characters (hyphens, colons, spaces) must be wrapped in square brackets:
- Variables with underscores only (like
current_day,subscriber_id) do NOT need brackets:- {{current_day}} Correct (has underscore)
- {{[random_number]}} Incorrect (square brackets not required)
- Test with empty data
- Ensure your templates render correctly when custom fields are empty.
- Use meaningful fallbacks
- Instead of generic "Customer", try context-specific fallbacks:
Hello {{or [First-Name] "Valued member"}}!
- Instead of generic "Customer", try context-specific fallbacks:
- Combine helpers for complex logic:
- Nest helpers to create sophisticated conditional logic:
- {{#if (and (eq [Country] "US") (gt [Order-Total] 50))}
- Nest helpers to create sophisticated conditional logic:
- Keep comparisons data type-appropriate:
- Use
gtandltonly with numeric values.- {{#if (lt [Days-Until-Expiration] 7)}} <p><strong>URGENT:</strong> Your membership expires in {{[Days-Until-Expiration]}} days!</p> {{/if}}
- Use
If your Handlebars aren't quite working how you'd like them to, here are some ways you can troubleshoot common problems that arise.
- Issue: Variable not displaying
- Solution: Check if the variable name has special characters (hyphens, colons, spaces) and wrap it in brackets
{{[First-Name]}},{{[todaysdate:Ymd]}}
- Note: Variables with only underscores don't need brackets
{{current_day}},{{subscriber_id}}
- Solution: Check if the variable name has special characters (hyphens, colons, spaces) and wrap it in brackets
- Issue: Comparison not working
- Solution: Ensure you're comparing compatible types (numbers with numbers, strings with strings)
- Issue: Syntax errors
- Solution: Verify all opening
{{#if}}tags have closing{{/if}}tags
- Solution: Verify all opening
- Issue:
gtorltnot working- Solution: These helpers only work with numeric values. Ensure your custom fields contain numbers.
Pinpointe Newsletter
Join the newsletter to receive the latest updates in your inbox.