You are here: WikiStart/Docs/Variables/DefaultValue


Setting default values for variables

When using the <patTemplate:var/> tag to include a variable in a template, it is possible to specify a default value, that will be used when no value is assigned to this variable from PHP. This can be achieved using the default attribute:

<patTemplate:tmpl name="page">
  Hello <patTemplate:var name="user" default="Guest"/>.
</patTemplate:tmpl>

As long, as no value is assigned to the variable user, this page will display:

Hello Guest.

Using the return value of a function

Since revision [438] (or patTemplate 3.1.0a3), it is possible to specify a PHP function or a static method that will be used to generate the default value for the variable. Again, the default attribute can be used:

<patTemplate:tmpl name="page">
  The current time is <patTemplate:var name="timestamp" default="time()"/>.
</patTemplate:tmpl>

This way you can include the current UNIX timestamp without having to write PHP code. As this poses a security risk (your template designers my call any PHP function), you have to enable this feature, so it can be used in the templates:

$tmpl = &new patTemplate();
$tmpl->setOption('allowFunctionsAsDefault', true);

To call a static method instead of a function, you need to specify the class name and the method name, separated by two colons:

<patTemplate:tmpl name="page">
  The current time is <patTemplate:var name="timestamp" default="MyClass::getTime()"/>.
</patTemplate:tmpl>

The functions and methods will be evaluated, when the template is read from the file. You are not able to access the value of the variable from this function. This is what variable modifiers should be used for.