Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a symfony twig filter?

Tags:

twig

symfony

For instance my bundle namespace is Facebook\Bundle\FacebookBundle\Extension.

Using this how can I create a twig extension ?

like image 718
Manish Basdeo Avatar asked Aug 10 '12 18:08

Manish Basdeo


People also ask

How do you use a Twig filter?

Variables in Twig can be modified with help of twig filters. Filters are simply separated from variables by a pipe symbol ( | ). For applying twig filter we only need to apply the ( | ) followed by filter name. Twig comes with many filters built into it, and Drupal has a variety of filters native to it.

What are Twig filters in Drupal?

Filters in Twig can be used to modify variables. Filters are separated from the variable by a pipe symbol. They may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.

Is Twig a Symfony?

Twig is the template engine used in Symfony applications. There are tens of default filters and functions defined by Twig, but Symfony also defines some filters, functions and tags to integrate the various Symfony components with Twig templates.


2 Answers

It's all here: How to write a custom Twig Extension.

1. Create the Extension:

// src/Facebook/Bundle/Twig/FacebookExtension.php
namespace Facebook\Bundle\Twig;

use Twig_Extension;
use Twig_Filter_Method;

class FacebookExtension extends Twig_Extension
{
    public function getFilters()
    {
        return array(
            'myfilter' => new Twig_Filter_Method($this, 'myFilter'),
        );
    }

    public function myFilter($arg1, $arg2='')
    {
        return sprintf('something %s %s', $arg1, $arg2);
    }

    public function getName()
    {
        return 'facebook_extension';
    }
}

2. Register an Extension as a Service

# src/Facebook/Bundle/Resources/config/services.yml
services:
    facebook.twig.facebook_extension:
        class: Facebook\Bundle\Twig\AcmeExtension
        tags:
            - { name: twig.extension }

3. Use it

{{ 'blah'|myfilter('somearg') }}
like image 105
noisebleed Avatar answered Oct 20 '22 21:10

noisebleed


You can also create twig functions by using the getFunctions()

class FacebookExtension extends Twig_Extension
{
    public function getFunctions()
    {
        return array(
            'myFunction' => new Twig_Filter_Method($this, 'myFunction'),
        );
    }

    public function myFunction($arg1)
    {
        return $arg1;
    }

Use your function like this:

{{ myFunction('my_param') }}
like image 16
Sybio Avatar answered Oct 20 '22 19:10

Sybio