Use PHP functions in TWIG templates

k0d3r1s
k0d3r1s
Jan 20, 2019 · 1 min read
Image for post
Image for post

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade