Skip to content

Instantly share code, notes, and snippets.

@tremby
Last active March 9, 2016 08:43
Show Gist options
  • Save tremby/cdf7ef824291554b6a80 to your computer and use it in GitHub Desktop.
Save tremby/cdf7ef824291554b6a80 to your computer and use it in GitHub Desktop.
Twig filter to make sure a variable is an array
<?php
namespace Tremby\Twig\Extension;
use Twig_Extension;
use Twig_SimpleFilter;
/**
* Filter to leave a variable alone if it's array,
* pass an empty array if the variable was missing,
* and wrap anything else in an array.
*/
class WrapArray extends Twig_Extension
{
public function getName()
{
return 'WrapArray';
}
public function getFilters()
{
return [
new Twig_SimpleFilter('wrapArray', function ($var) {
if ($var === null) {
return [];
}
if (!is_array($var)) {
return [$var];
}
return $var;
}),
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment