Skip to content

Instantly share code, notes, and snippets.

@mylk
Last active August 14, 2016 14:18
Show Gist options
  • Save mylk/81501a2abb416afc4b628e3f215576d8 to your computer and use it in GitHub Desktop.
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
<?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