Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter boolean variable in a twig template

Tags:

twig

symfony

I have a boolean variable(0, 1) in my database and I want to filter it to a word 0 for 'NO', and 1 for 'Yes'. how can I do that in a twig template

I want something like {{ bool_var | '??' }} where the '??' is the filter

like image 900
anyavacy Avatar asked Jul 11 '14 20:07

anyavacy


2 Answers

Quick way to achieve that is to use the ternary operator:

{{ bool_var ? 'Yes':'No' }} 

http://twig.sensiolabs.org/doc/templates.html#other-operators

You could also create a custom filter that would do this. Read about custom TWIG extensions - http://symfony.com/doc/current/cookbook/templating/twig_extension.html

like image 136
dmnptr Avatar answered Sep 19 '22 14:09

dmnptr


To build on what @dmnptr said in his last paragraph, in your app bundle, create a /Twig folder and create an AppExtension class inside.

class AppExtension extends \Twig_Extension {     public function getFilters()     {         return array(             new \Twig_SimpleFilter('boolean', array($this, 'booleanFilter')),         );     }      public function booleanFilter($value)     {         if ($value) {             return "Yes";         } else {             return "No";         }     }      public function getName()     {         return 'app_extension';     } } 

Then, in your bundle's Resources/config/ folder, add the following to your services.yml where class is the class of the new class:

app.twig_extension:     class: [YourAppBundleNamespace]\Twig\AppExtension     public: false     tags:         - { name: twig.extension } 

The filter will be available in Twig by simply appending a |boolean to any variable.

like image 39
bassplayer7 Avatar answered Sep 19 '22 14:09

bassplayer7