Use PHP functions in TWIG templates

k0d3r1s
1 min readJan 20, 2019

--

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 }}

or dynamically any php function:

{{ raven_function('count', users) }}{{ user.name|raven_filter('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

or without any arguments if you want to use dynamic function / filters:

# config/services.yaml
services:
ravenflux.twig.extension.php_functions:
class: RavenFlux\Twig\PhpFunctionsExtension
tags:
-
name: twig.extension

--

--