Backslash Escape + #if Conditional Syntax
1. Backslash \ Escape Rules
Pre‑defined variable:#set($dog = "woof woof")
| VTL Code | Rendered Output | Explanation |
|---|---|---|
$dog | woof woof | Normal variable resolution |
\$dog | $dog | Single backslash: escapes the following $, disables variable parsing and prints $ literally |
\\$dog | \woof woof | First \ escapes second \ → outputs \;remaining $dog resolves normally |
\\\$dog | \$dog | \\ outputs \, \$ outputs $ |
\\\\$dog | \woof woof | \\ outputs \, \\ outputs \;$dog resolves variable |
- Velocity variable names must start with a letter,
$10.0will not be treated as variable and outputs as‑is;so writingMicrosoft $10.0 USDin text requires no extra escaping; - Consecutive backslashes cancel out in pairs;only the
\$combination can escape dollar‑sign; - To display
$variableNameliterally on page, standard syntax:\$dog.
2. #if Branch Conditional Syntax
#set($ages = 22)
#if ($ages <13)
<h1>You are a child</h1>
#elseif ($ages <18)
<h1>You are a teenager</h1>
#elseif ($ages <35)
<h1>You are a young adult</h1>
#elseif ($ages <60)
<h1>You are middle‑aged</h1>
#else
<h1>You are elderly</h1>
#endCode language: PHP (php)
Execution Result
$ages=22, satisfies 22 < 35 → output:<h1>You are a young adult</h1>
Notes
- You must close block with
#end, missing it will trigger parsing error; - Keyword:
#elseif(do NOT write as #else if, that is invalid syntax); - Supported operators:
< > <= >= == != && ||and more; - Matching rule: evaluate conditions top‑down. Once one branch matches, subsequent branches are skipped.
Escape characters and #if conditionals
Previous: Extension methods