Use PHP function in TWIG?

2019-02-06 03:12发布

问题:

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?

回答1:

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



回答2:

// $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:

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.



回答4:

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



标签: php symfony twig