Use PHP functions in TWIG templates

ravenflux/php-functions is TWIG extension that implements a way to use native PHP functions and filters in TWIG template.


Function VS Filter

source

A function is used when you need to compute things to render the result.
A filter is a way to transform the displayed data.


Usage

{{ count(users) }}
{{ user.name|nl2br }}

Installation

The recommended way to install is via Composer:

composer require ravenflux/php-functions

For Symfony usage add it as a service and tag it:

# config/services.yaml
parameters:
ravenflux_functions:
- 'count'
ravenflux_filters:
- 'nl2br'

services:
ravenflux.twig.extension.php_functions:
class: RavenFlux\Twig\PhpFunctionsExtension
arguments:
- '%ravenflux_functions%'
- '%ravenflux_filters%'
tags:
-
name: twig.extension

or inline without extra parameters:

# config/services.yaml
services:
ravenflux.twig.extension.php_functions:
class: RavenFlux\Twig\PhpFunctionsExtension
arguments:
- #first argument are functions
- 'count'
- #second argument are filters
- 'nl2br'
tags:
-
name: twig.extension