15

In PHP templates I can use php functions, for example:

foreach ($users as $user){
  echo someFunction($user->getName());
}

How can I make it in TWIG?

{% for user in users %}
    * {{ user.name }}
{% else %}
    No user have been found.
{% endfor %}

How do I achieve this?

4 Answers 4

13

What you need are functions or filters. You can easily add these using the examples.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you include a bit of details about the implementation? Should the function and the instantiation of the "Twig_Environment" class be included in the controller? Should the object "$twig = new Twig_Environment($loader)" be passed as a variable (e.g. 'twig'=>$twig) to the rendered template? What should be included in the "/path/to/templates" in the definition "$loader = new Twig_Loader_Filesystem('/path/to/templates');". Is that the path to the templates in my bundle? does it need to be absolute? It does not work for me. An example would be most appreciated...
For anyone coming here and wanting an example, there's a very good and simple example in the Twig documentation at sensiolabs: twig.sensiolabs.org/doc/advanced.html#functions
FYI: Links are dead
11
// $twig is a Twig_Environment instance.

$twig->registerUndefinedFunctionCallback(function($name) {
    if (function_exists($name)) {
        return new Twig_SimpleFunction($name, function() use($name) {
            return call_user_func_array($name, func_get_args());
        });
    }
    throw new \RuntimeException(sprintf('Function %s not found', $name));
});

In a twig template:

{{ explode(",", "It's raining, cats and dogs.").0 | raw }}

this will output "It's raining". By default, returned values are escaped in Twig.

Twig_SimpleFunction is the preferred class to use. All other function related classes in Twig are deprecated since 1.12 (to be removed in 2.0).

In a Symfony2 controller:

$twig = $this->get('twig');

3 Comments

where should be this registered in standard symfony2 app?
This should never, ever be used as it's terribly insecure.
Not really, it doesn't suddenly turn into a wordpress. But templates should only render HTML/Javascript using available data.
1

There is already a Twig extension that lets you call PHP functions form your Twig templates like:

Hi, I am unique: {{ uniqid() }}.

And {{ floor(7.7) }} is floor of 7.7.

See official extension repository.

Comments

0

If you're working in symfony 2 this should also help. Concept is the same but you put the code somewhere else and format it a little differently.

http://symfony.com/doc/2.0/cookbook/templating/twig_extension.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.