ViewFish Templating
Default Values
You can provide a fallback value for any variable using the default pipe function. If the variable is missing or empty, the default value will be used instead.
Syntax
{{variable|default:"fallback value"}}
You can also use single quotes:
{{variable|default:'fallback value'}}
Example
Template:
<p>Hello, {{name|default:"Anonymous"}}!</p>
<p>Role: {{role|default:"Guest"}}</p>
<p>Location: {{city|default:"Unknown"|ucwords}}</p>
PHP:
// With data:
echo $t->render($template, ['name' => 'Alice', 'city' => 'portland']);
// Output: Hello, Alice! Role: Guest. Location: Portland
// Without data:
echo $t->render($template, []);
// Output: Hello, Anonymous! Role: Guest. Location: Unknown
Chaining with other functions
The default function can be chained with other pipe functions. When a value is present, default passes it through unchanged and subsequent functions apply normally:
{{name|default:"anonymous"|ucfirst}}
If name is "alice", output is Alice. If name is missing, output is Anonymous.
How it works
- If the variable exists in your data array and is non-empty,
defaultis ignored and the real value is used. - If the variable is missing entirely from the data array, the
defaultvalue is substituted. - This works with both
{{var|default:"x"}}and{{$var|default:"x"}}syntax.
You can see this in action in Example 9.