Last active
August 14, 2016 14:18
-
-
Save mylk/81501a2abb416afc4b628e3f215576d8 to your computer and use it in GitHub Desktop.
Twig filter that returns a default value if the given one is null
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Installation: | |
* ============= | |
* # services.yml | |
* services: | |
* # ... | |
* acme.twig.if_null_extension: | |
* class: Acme\AcmeBundle\Twig\IfNullExtension | |
* tags: | |
* - { name: twig.extension } | |
* | |
* Usage: | |
* ====== | |
* {{ entity.lastName | ifNull("-") }} | |
*/ | |
namespace Acme\AcmeBundle\Twig; | |
class IfNullExtension extends \Twig_Extension | |
{ | |
public function getFilters() | |
{ | |
return array( | |
new \Twig_SimpleFilter("ifNull", array($this, "ifNullFilter")) | |
); | |
} | |
public function ifNullFilter($value, $default) | |
{ | |
if (null === $value) { | |
return $default; | |
} else { | |
return $value; | |
} | |
} | |
public function getName() | |
{ | |
return "ifNull_extension"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment