Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible or not to use a native php function in Twig?

I am a newbie on Symfony. How can I use a native php function in a twig template?

For example I want to use the function chr in a loop like this:

{% for directory in directories %}
    chr(loop.index)
{% endfor %}
like image 793
user777897 Avatar asked Mar 14 '13 15:03

user777897


People also ask

Can I use PHP in Twig?

No this is not possible. If you really need PHP, you can write a plugin with one of the following: a Template Variable class, which can be accessed from your templates via craft.

Is Twig a Symfony?

Twig is a PHP template engine. It was created by Symfony developers. Twig files have the extension of . html.


2 Answers

Twig allows you to add functions and filters. There're multiple examples on the documentation.

For example,

like image 63
Ahmed Siouani Avatar answered Sep 23 '22 23:09

Ahmed Siouani


No, you can't use PHP directly in Twig.

There are some options:

Use PHP as the templating engine

You can set PHP as the templating engine instead of twig. This means you use PHP inside your templates and you can use all native PHP functions. See this doc article on how to do that.

Create a Twig extension

You could easilly create your own Twig extension. The best practise is to create a AcmeTwigBundle where you put all those common Twig extensions. See this doc article on how to do that in Symfony.

As of Twig 1.12 (Symfony2.2 comes with it), there is a really nice class which allows you to easilly map a PHP function to a twig function:

new Twig_SimpleFilter('rot13', 'str_rot13');

This will create a rot13 Twig function which maps to the str_rot13 PHP function.

like image 30
Wouter J Avatar answered Sep 20 '22 23:09

Wouter J