Ray Kootstra Ray Kootstra - 4 months ago
220 0

Example of an Symfony2 Twig extention with a function.
Use it like this (in Twig):

{{ get_function_name() }}

PHP

Symfony2 Twig extention function

<?php

namespace AppBundle\Twig;

/**
 * MyTwigExtension
 */
class MyTwigExtension extends \Twig_Extension
{
    /**
     * @{inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction(
                'get_function_name',
                array($this, 'getFunctionName')
            )
        );
    }

    /**
     * @{inheritdoc}
     */
    public function getName()
    {
        return 'my_twig_extension';
    }

    /**
     * @return String
     */
    public function getFunctionName()
    {
        return 'Hello World';
    }
}
Comments