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
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
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.
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