Conditionals

The {#if} block conditionally renders its contained content based on a truthy/falsy evaluation of an expression.

Basic syntax

{#if Condition}
…content rendered when Condition is truthy…
{/if}
Data:
var person = new
{
    IsEmployed = true,
    Employer = "Hat Trick Labs",
    Name = new { First = "John", Last = "Doe" }
};
Template:
Hello {Name.First} {Name.Last},
{#if IsEmployed}
We see you are currently employed at {Employer}.
{/if}
{#if !IsEmployed}
We see you are currently unemployed.
{/if}
Result:
Hello John Doe,
We see you are currently employed at Hat Trick Labs.

Negation

Prefix the expression with ! to negate it. {#if !IsEmployed} renders when IsEmployed is falsy.

There is no {#else} or {#elseif} tag. Mutually exclusive branches are expressed as a pair of conditionals — one against the expression, one against its negation — as shown above.

Falsy values

{#if} uses the engine’s standard falsy ruleset — see Core Concepts for the full list.

A missing member is not falsy — it throws. {#if Foo} where Foo does not exist on the bound object raises a MergeException. Supply a null or false default in the bound data to branch on possibly-absent state.

Conditional expressions

The {#if} tag accepts the same expression forms as a simple tag:

  • A bind expression — {#if Address.City}
  • A $ local-scope reference — {#if $}
  • A declared variable — {#if :myVar}
  • A lambda call — {#if (Items) => hasAny}
  • A negated form of any of the above — {#if !Address.City}, {#if !(Items) => hasAny}

Boolean and numeric literals are not supported as conditions. To gate on a constant for testing, register a lambda that returns the desired value.

Nested conditionals

{#if} blocks can be nested freely within other block tags ({#if}, {#each}, {#with}, partials). Each nested block participates in the engine’s stack-depth budget; see Stack Depth Limit.

Whitespace

Block tags introduce newline artifacts by default. Use the - trim marker ({-#if …-}) or set TrimWhitespace = true on the engine to suppress them. See Whitespace Control for the full ruleset.

Next steps

  • Iteration — render a block per item in a collection
  • Variables — declare values once and condition on them later
  • Lambda Expressions — use a function to compute a richer condition