Created
August 16, 2017 14:14
-
-
Save cviebrock/321494afffb2ca22d8705423951d2bf1 to your computer and use it in GitHub Desktop.
Twig `compact` function
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 | |
class CompactFunction extends Twig_Extension | |
{ | |
/** | |
* @inheritdoc | |
*/ | |
public function getFunctions() | |
{ | |
return [ | |
new Twig_SimpleFunction('compact', [$this, 'compact'], | |
[ | |
'needs_context' => true, | |
'is_variadic' => true, | |
] | |
), | |
]; | |
} | |
/** | |
* Return a compacted array, grabbing only the items from the | |
* context that are specified in the given keys. | |
* | |
* @param array $context | |
* @param array $keys | |
* | |
* @return array | |
*/ | |
public function compact(array $context, array $keys = []) | |
{ | |
return array_intersect_key($context, array_flip((array) $keys)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See twigphp/Twig#2532 for context.