Conditionals Guide¶
Conditionals let you show or hide content in your document based on data values. They're perfect for creating flexible templates that adapt to different scenarios.
Basic Conditional Syntax¶
Simple If Statement¶
When content is shown:
- Variable exists and is true
- Variable exists and is not empty/zero/false
Falsy values (content is hidden): missing/null, false, empty or whitespace text, the text "false" or "0" (any casing, e.g. "False"), any numeric zero (0, 0.0, 0.00, JSON 0.0, and zero of every numeric type such as decimal or long), NaN, and empty lists. Everything else is truthy, including any other text ("no" is truthy!).
Misspelled or missing variables are silently false:
{{#if IsActiv}}never shows its content. When a developer validates the template with data (ValidateTemplate), a condition that tests a missing variable on its own ({{#if Missing}},{{#if not Missing}},{{#if A and Missing}}, also in{{#elseif}}) produces aMissingConditionVariablewarning. Use{{#if Missing exists}}or{{#if Missing is empty}}when a variable is meant to be optional: those checks are not reported.Markers in their own paragraphs: in the block form, each marker (
{{#if}},{{#elseif}},{{#else}},{{/if}}) should be alone in its paragraph. A marker paragraph is removed completely, so any other text in it is lost. To change only part of a paragraph, put all markers in that paragraph (inline conditionals).Marker keywords are case-insensitive (
{{#IF}}works), but variable names are not.
JSON:
Template:
Dear Customer,
{{#if IsVIP}}
Thank you for being a VIP member! You get 20% off today.
{{/if}}
Best regards
Output (when IsVIP is true):
If-Else Statement¶
JSON:
Template:
{{#if IsPremium}}
Welcome, Premium Member! Enjoy unlimited access.
{{#else}}
Upgrade to Premium to unlock all features.
{{/if}}
Output:
If-ElseIf-Else Statement¶
Use {{#elseif}} to check multiple conditions in sequence:
{{#if Condition1}}
Content for condition 1
{{#elseif Condition2}}
Content for condition 2
{{#elseif Condition3}}
Content for condition 3
{{#else}}
Default content
{{/if}}
JSON:
Template:
{{#if Score >= 90}}
Grade: A - Excellent!
{{#elseif Score >= 80}}
Grade: B - Good
{{#elseif Score >= 70}}
Grade: C - Satisfactory
{{#elseif Score >= 60}}
Grade: D - Needs Improvement
{{#else}}
Grade: F - Please see instructor
{{/if}}
Output:
How it works:
- Conditions are evaluated in order, from top to bottom
- The first condition that is true wins - its content is shown
- All other branches are removed
- The {{#else}} branch is optional and acts as a fallback
- Important: {{#else}} must always be the last branch
Benefits over nested conditionals: - Cleaner, more readable templates - Easier to add/remove conditions - Less indentation and fewer closing tags
Comparison Operators¶
Equality (=)¶
Check if two values are equal:
JSON:
Template:
{{#if Status = "Active"}}
Your account is active and ready to use.
{{/if}}
{{#if Status = "Pending"}}
Your account is pending approval.
{{/if}}
Tips:
- Use quotes around text values: Status = "Active"
- Numbers don't need quotes: Age = 18
- Numbers are compared by value, regardless of how they are stored: Price = 10 matches 10, 10.0 and 10.00, and JSON 10.50 matches Price = 10.5
- A number compared with quoted text compares the text form: Count = "5" matches 5 but not 5.0
- Comparison is case-sensitive: "active" β "Active"
- true/false compare case-insensitively with text: IsActive = "True" matches the boolean true
- An unquoted word that is not a variable is compared as text: Status = Active works like Status = "Active" when there is no variable named Active. Prefer quotes: a variable named Active would silently be used instead
Inequality (!=)¶
Check if two values are NOT equal:
JSON:
Template:
This message only shows when payment is NOT paid.
Greater Than (>)¶
JSON:
Template:
{{#if Age > 18}}
You are eligible to vote.
{{/if}}
{{#if Score > 90}}
Excellent work! You earned an A grade.
{{/if}}
Less Than (<)¶
JSON:
Template:
{{#if Temperature < 0}}
β οΈ Freezing conditions - take precautions.
{{/if}}
{{#if Stock < 5}}
β οΈ Low stock alert - only {{Stock}} items remaining.
{{/if}}
Greater Than or Equal (>=)¶
JSON:
Template:
{{#if YearsExperience >= 5}}
You qualify for the Senior Developer position.
{{/if}}
{{#if OrderAmount >= MinimumOrder}}
β Order qualifies for free shipping!
{{/if}}
Less Than or Equal (<=)¶
JSON:
Template:
{{#if ItemsInCart <= 5}}
Add more items to qualify for bulk discount!
{{/if}}
{{#if DaysUntilExpiry <= 7}}
β οΈ Your subscription expires soon - renew now!
{{/if}}
Logical Operators¶
AND Operator¶
Both conditions must be true:
JSON:
Template:
{{#if Age >= 18 and HasLicense}}
You can rent a car.
{{/if}}
{{#if HasLicense and HasInsurance}}
You're approved for vehicle rental.
{{/if}}
OR Operator¶
At least one condition must be true:
JSON:
Template:
{{#if IsVIP or IsPremium}}
You have access to exclusive features.
{{/if}}
{{#if Role = "Admin" or Role = "Moderator"}}
You have moderation permissions.
{{/if}}
NOT Operator¶
Negates a condition:
JSON:
Template:
{{#if not IsExpired}}
Your subscription is active.
{{/if}}
{{#if not IsBanned}}
Welcome back! Your account is in good standing.
{{/if}}
Combining Multiple Operators¶
JSON:
Template:
{{#if Age >= 18 and (Country = "USA" or HasPassport) and not IsBanned}}
You are eligible to travel internationally.
{{/if}}
Operator precedence (loosest to tightest): or β and β not β comparisons (=, ==, !=, >, <, >=, <=, in, contains, startswith, endswith) β exists / is empty / is not empty. Parentheses override everything.
This means:
- A or B and C is A or (B and C)
- not Status = "Active" is not (Status = "Active"): comparisons are evaluated before not
- not A and B is (not A) and B
Word operators are case-insensitive (AND, Or). &&, ||, === and <> are not supported.
Membership, String, and Existence Checks¶
Membership (in)¶
Check whether a value appears in a collection. The right side can be a collection variable, a list literal in parentheses, or a comma-separated string (items are trimmed, so "Admin, Editor" works too):
JSON:
Template:
{{#if Role in Roles}}
You have access to the content management system.
{{/if}}
{{#if Role in ("Admin", "Editor")}}
You can publish articles.
{{/if}}
{{#if Role in "Admin,Editor,Viewer"}}
You are a recognized role.
{{/if}}
Negate membership with not:
String Checks (contains, startswith, endswith)¶
JSON:
Template:
{{#if Description contains "urgent"}}
β οΈ Priority handling required.
{{/if}}
{{#if OrderCode startswith "US-"}}
Domestic order.
{{/if}}
{{#if FileName endswith ".pdf"}}
PDF attachment included.
{{/if}}
Note: Like =, these string comparisons are case-sensitive.
On lists: when the left side is a list, contains checks membership (an element equal to the value, like "urgent" in Tags), not a substring:
startswith / endswith on a list are always false.
Existence (exists, is empty, is not empty)¶
exists checks that a variable is present, regardless of its value. is empty / is not empty check whether a value is missing, null, blank, or an empty collection.
JSON:
Template:
{{#if Notes exists}}
The Notes field was provided.
{{/if}}
{{#if Notes is empty}}
No notes were added.
{{/if}}
{{#if Notes is not empty}}
Notes: {{Notes}}
{{/if}}
A missing variable is treated as empty. A variable that is present but explicitly null satisfies both exists and is empty. Numbers and booleans are never empty.
Variables Named Like Keywords¶
in, contains, startswith, endswith, exists, is and empty are keywords only where an operator is expected, so {{#if Exists}} or {{#if Empty = "yes"}} still read the variables Exists and Empty. To make the intent explicit (and for And, Or, Not, True, False, Null), put the name in square brackets:
and, or, not, true, false and null are always keywords, so a variable with one of these names can only be used with brackets. When a developer validates a template with data (ValidateTemplate), a keyword used as a variable name that exists in the data produces a ReservedWordAsVariable warning.
Quotes Inside Text¶
Text values use double quotes. Use \" for a quote and \\ for a backslash inside a quoted text value (other backslashes are kept, so "C:\Temp" also works). Word's typographic quotes (ββ¦β) are converted to straight quotes automatically. Single quotes ('...') are not string delimiters in {{#if}} (they are in inline {{(...)}} expressions):
Grouping with Parentheses¶
Use parentheses to control evaluation order, the same as in boolean expressions:
Reminder on precedence: and binds tighter than or (A or B and C means A or (B and C)), and not applies to a whole comparison (not A = B means not (A = B)). Use parentheses whenever you want a different grouping.
Common Patterns¶
Boolean Flags¶
JSON:
Template:
{{#if ShowHeader}}
=== HEADER SECTION ===
Company Name | Contact Info
{{/if}}
[Main content here]
{{#if ShowFooter}}
=== FOOTER SECTION ===
Β© 2024 Company Name
{{/if}}
Status Checks¶
JSON:
Template:
Order Status:
{{#if OrderStatus = "Pending"}}
β³ Your order is being processed.
{{/if}}
{{#if OrderStatus = "Shipped"}}
π¦ Your order has been shipped!
{{/if}}
{{#if OrderStatus = "Delivered"}}
β Your order was delivered.
{{/if}}
{{#if OrderStatus = "Cancelled"}}
β This order was cancelled.
{{/if}}
Tiered Messaging¶
Use {{#elseif}} for cleaner tiered content:
JSON:
Template:
Your Score: {{Score}}
{{#if Score >= 90}}
π Outstanding! You achieved an A grade.
{{#elseif Score >= 80}}
π Great job! You achieved a B grade.
{{#elseif Score >= 70}}
β Good work! You achieved a C grade.
{{#else}}
π Keep studying! You can improve.
{{/if}}
Output:
Tip: Use {{#elseif}} instead of nested {{#if}} blocks for cleaner, more maintainable templates.
Access Control¶
JSON:
Template:
{{#if IsAuthenticated}}
Welcome to the dashboard!
{{#if UserRole = "Admin"}}
[Admin Panel]
- User Management
- System Settings
- Reports
{{/if}}
{{#if UserRole = "Editor"}}
[Editor Panel]
- Edit Content
- Publish Articles
{{/if}}
{{#if UserRole = "Viewer"}}
[Viewer Panel]
- View Content Only
{{/if}}
{{#else}}
Please log in to access this page.
{{/if}}
Working with Numbers¶
Range Checks¶
JSON:
Template:
{{#if Age >= 18 and Age < 65}}
Adult pricing applies.
{{/if}}
{{#if Temperature >= 60 and Temperature <= 80}}
Perfect weather today!
{{/if}}
{{#if Price > 100 and Price <= 200}}
Mid-range product pricing.
{{/if}}
Inventory Checks¶
JSON:
Template:
{{#if StockLevel = 0}}
β OUT OF STOCK
{{#else}}
{{#if StockLevel < ReorderPoint}}
β οΈ LOW STOCK: {{StockLevel}} remaining
{{#else}}
β In Stock: {{StockLevel}} available
{{/if}}
{{/if}}
Discount Qualification¶
JSON:
Template:
{{#if OrderTotal >= 100 or IsFirstOrder or LoyaltyPoints >= 1000}}
π You qualify for a discount!
{{#if OrderTotal >= 100}}
- Free shipping on orders over $100
{{/if}}
{{#if IsFirstOrder}}
- 15% off first order discount
{{/if}}
{{#if LoyaltyPoints >= 1000}}
- Loyalty member discount available
{{/if}}
{{/if}}
Working with Text¶
Text Comparison¶
Remember: text comparisons are case-sensitive!
JSON:
Template:
{{#if Category = "Electronics"}}
Shipping: 2-3 business days
{{/if}}
{{#if Category = "electronics"}}
This won't match - wrong case!
{{/if}}
{{#if Priority = "high"}}
β οΈ HIGH PRIORITY ORDER
{{/if}}
Multiple Text Options¶
JSON:
Template:
{{#if PaymentMethod = "Credit Card" or PaymentMethod = "Debit Card"}}
Card payment processing fee: $2.50
{{/if}}
{{#if PaymentMethod = "PayPal" or PaymentMethod = "Venmo"}}
Online payment processing fee: 3%
{{/if}}
{{#if PaymentMethod = "Cash" or PaymentMethod = "Check"}}
No processing fees!
{{/if}}
Inline Conditionals¶
When {{#if}} and {{/if}} are in the same paragraph, only that part of the paragraph is affected:
Only the text of the markers and of the branches that are not shown is removed. Everything else in the paragraph stays exactly as it was: the formatting of each piece of text, hyperlinks, fields (such as page numbers), tabs, line breaks, images and footnote references.
Non-text content that is placed inside a branch belongs to that branch: an image, line break,
footnote reference or complete field between {{#if}} and {{/if}} is removed when the branch is not shown.
Bookmarks are always kept.
Inline conditionals support {{#elseif}} and {{#else}} as well:
For a single true/false value, an inline expression such as {{(Score >= 90):yesno}} is another option; note that inline expressions follow slightly different truthiness rules.
Nested Conditionals¶
You can nest conditionals inside each other:
JSON:
Template:
{{#if IsLoggedIn}}
Welcome!
{{#if UserType = "Premium"}}
{{#if HasActiveSubscription}}
[Premium Content Unlocked]
Access to all features!
{{#else}}
[Subscription Expired]
Please renew your subscription.
{{/if}}
{{#else}}
[Free Account]
Upgrade to Premium for more features.
{{/if}}
{{#else}}
Please log in.
{{/if}}
Best Practice: Limit nesting to 2-3 levels deep to keep templates readable.
Conditional Table Rows¶
To show or hide whole table rows, put each marker ({{#if}}, {{#elseif}}, {{#else}}, {{/if}}) in its own row:
| Item | Amount |
|---|---|
| Subtotal | {{Subtotal}} |
| {{#if HasDiscount}} | |
| Discount | {{Discount}} |
| {{#else}} | |
| No discount applied | |
| {{/if}} | |
| Total | {{Total}} |
- The marker rows are always removed.
- The rows of the first matching branch are kept; the rows of all other branches are removed.
- Conditional rows can be nested and can be used inside table row loops, where they are evaluated for each item.
- If every row of a table is removed, the whole table is removed.
A conditional whose start and end markers are inside one cell (inline or on separate paragraphs) only affects the content of that cell.
Conditionals with Loops¶
You can use conditionals inside loops:
JSON:
{
"Products": [
{ "Name": "Widget", "Price": 10, "InStock": true },
{ "Name": "Gadget", "Price": 25, "InStock": false },
{ "Name": "Doohickey", "Price": 15, "InStock": true }
]
}
Template:
Product List:
{{#foreach Products}}
- {{Name}}: ${{Price}}
{{#if InStock}}
β Available
{{#else}}
β Out of Stock
{{/if}}
{{/foreach}}
Output:
Product List:
- Widget: $10
β Available
- Gadget: $25
β Out of Stock
- Doohickey: $15
β Available
Loop Variables in Conditionals¶
Use loop-specific variables in conditionals:
JSON:
Template:
{{#foreach Items}}
{{#if @first}}*** First item: {{.}} ***{{/if}}
{{#if not @first and not @last}}- {{.}}{{/if}}
{{#if @last}}*** Last item: {{.}} ***{{/if}}
{{/foreach}}
Output:
Common Use Cases¶
Personalized Greetings¶
JSON:
Template:
Dear {{CustomerName}},
{{#if DaysSinceLastPurchase < 30}}
Great to see you again so soon!
{{#else}}
We've missed you! It's been a while since your last visit.
{{/if}}
{{#if DaysSinceLastPurchase > 60}}
Here's a 15% discount to welcome you back!
{{/if}}
Terms and Conditions¶
JSON:
Template:
TERMS AND CONDITIONS
{{#if IncludeWarranty}}
1. Warranty Coverage
This product includes a 2-year manufacturer warranty...
{{/if}}
{{#if IncludeInsurance}}
2. Insurance Policy
Additional insurance coverage provides...
{{/if}}
{{#if IncludeExtendedSupport}}
3. Extended Support
24/7 customer support is included for...
{{/if}}
Regional Content¶
JSON:
Template:
{{#if Country = "USA"}}
Customer Service: 1-800-555-0123
Business Hours: 9 AM - 5 PM EST
{{/if}}
{{#if Country = "UK"}}
Customer Service: 0800 123 4567
Business Hours: 9 AM - 5 PM GMT
{{/if}}
{{#if Country = "Germany"}}
Kundenservice: 0800 123 4567
GeschΓ€ftszeiten: 9:00 - 17:00 Uhr MEZ
{{/if}}
Troubleshooting¶
Conditional Not Working¶
Check these common issues:
- Syntax errors:
- β
{{#if Status = "Active"}} - β
{{#elseif Status = "Pending"}} - β
{{if Status = "Active"}}(missing#) - β
{{elseif Status = "Pending"}}(missing#) - β
{{#if Status = "Active"(missing closing}}) - β
{{#if A && B}},{{#if A || B}},{{#if Status eq "x"}},{{#if Name = "open}}(not valid conditions; useand,or,=and closed quotes)
A condition that cannot be parsed is treated as false, and processing reports an ExpressionFailed warning (see ProcessingResult.Warnings). ValidateTemplate reports it as an InvalidConditionalExpression error.
Structural errors such as a missing {{/if}} or an {{#elseif}} after {{#else}} make processing fail (IsSuccess = false, with ErrorMessage set).
- Missing closing tag:
- β
{{#if ...}}...{{/if}} -
β
{{#if ...}}...{{#endif}}(wrong closing tag) -
Case sensitivity:
- β
{{#if Status = "Active"}}with JSON:"Status": "Active" -
β
{{#if Status = "active"}}with JSON:"Status": "Active"} -
Equality operator:
- β
{{#if Age = 18}}(single=for equality) -
β
{{#if Age == 18}}(double==also accepted) -
Quotes around text:
- β
{{#if Name = "Alice"}} - β οΈ
{{#if Name = Alice}}works only while there is no variable namedAlice(the unquoted word is then compared as text). Always quote text. -
β οΈ A misspelled variable on the left is compared as its own name:
{{#if Stauts = "Stauts"}}is true. CheckProcessingResult/validation for missing variables. -
Comparing numbers stored as text:
- β
{{#if Age > 18}}with JSON:"Age": 25(number) - β
{{#if Age > 18}}with JSON:"Age": "25"also works:>,<,>=,<=read numeric text as a number -
β οΈ
=compares a number with text by its text form:Count = "5"matches5, butPrice = "10"does not match10.00. Store numbers as numbers. -
Ordering with missing values:
>/<with a value that isnulltreat it as0; a comparison that cannot be done as numbers (for example with plain text) is false.
Content Always Shows/Never Shows¶
Debug steps:
-
Print the variable value to see what you're working with:
-
Check JSON structure:
-
Simplify the condition: Start with a simple boolean:
Nested Conditionals Not Working¶
Make sure each {{#if}} has a matching {{/if}}:
β Wrong:
β Correct:
ElseIf Not Working¶
Common mistakes:
-
Wrong order - else before elseif:
-
Missing
#in elseif: - β
{{#elseif Condition}} -
β
{{elseif Condition}}(missing#) -
Wrong syntax variants:
- β
{{#elseif Condition}} - β
{{else if Condition}}(wrong - no space) - β
{{#else if Condition}}(wrong syntax) - β
{{#elif Condition}}(elif is not supported)
Best Practices¶
- Keep conditions simple - Break complex logic into multiple simpler conditions
- Use meaningful variable names -
IsEligibleForDiscountis better thanFlag1 - Test edge cases - What happens when values are null, zero, empty, etc.?
- Add comments in Word - Use Word comments to document complex conditional logic (comments are not processed)
- Use else clauses - Provide feedback for both true and false cases when appropriate
- Use elseif for multiple conditions - Prefer
{{#elseif}}over deeply nested{{#if}}blocks - Keep else last - The
{{#else}}branch must always be the final branch before{{/if}} - Limit nesting - Deep nesting is hard to read; with
{{#elseif}}, you often don't need nesting at all
Next Steps¶
- Loops Guide - Repeat content for arrays and lists
- Boolean Expressions - Advanced boolean expression techniques
- Placeholders Guide - Using variables in your templates
- Template Syntax Reference - Complete syntax guide
- Examples Gallery - Real-world examples
Related Topics¶
- Format Specifiers - Display boolean values as Yes/No, checkboxes, etc.
- Best Practices - Tips for maintainable templates
- JSON Basics - Understanding your data structure