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 %}
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.
Twig is a PHP template engine. It was created by Symfony developers. Twig files have the extension of . html.
Twig allows you to add functions and filters. There're multiple examples on the documentation.
For example,
No, you can't use PHP directly in Twig.
There are some options:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With