Skip to main content

Filters

Filters in PHP-Jinja allow you to modify variables before they are rendered in templates.

Using Filters

Filters are applied to variables using the pipe (|) symbol:

{{ variable | filter }}

You can chain multiple filters, which are applied from left to right:

{{ variable | filter1 | filter2 | filter3 }}

Some filters accept arguments:

{{ variable | filter(arg1, arg2) }}

Available Filters

PHP-Jinja implements the following filters:

FilterDescriptionExampleResult
upperConvert to uppercase{{ "hello" | upper }}HELLO
lowerConvert to lowercase{{ "HELLO" | lower }}hello
capitalizeCapitalize first letter of each word{{ "hello world" | capitalize }}Hello World
trimRemove whitespace from start/end{{ " hello " | trim }}hello
replaceReplace occurrences of a substring{{ "hello" | replace("h", "j") }}jello
lengthGet string or array length{{ "hello" | length }}5
defaultDefault value for undefined variables{{ undefined | default("Guest") }}Guest
joinJoin array elements with a delimiter{{ ["a", "b"] | join("-") }}a-b
splitSplit a string into an array{{ "a-b" | split("-") }}["a", "b"]

Examples

String Manipulation

{{ "hello world" | capitalize | replace("world", "everyone") }}

Output: Hello everyone

Arrays

{{ ["apple", "banana", "orange"] | join(", ") | upper }}

Output: APPLE, BANANA, ORANGE

Default Values

The default filter is especially useful for handling undefined variables:

{{ username | default("Guest") }}

This displays the value of username if it exists, or "Guest" if it doesn't, without throwing an error.

Security Note

PHP-Jinja does not automatically escape HTML output. When displaying user-generated content, you should manually escape it to prevent XSS vulnerabilities:

$variables['userContent'] = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

Then in your template:

{{ userContent }}