Skip to content

Instantly share code, notes, and snippets.

@cviebrock
Created August 16, 2017 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cviebrock/321494afffb2ca22d8705423951d2bf1 to your computer and use it in GitHub Desktop.
Save cviebrock/321494afffb2ca22d8705423951d2bf1 to your computer and use it in GitHub Desktop.
Twig `compact` function
<?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));
}
}
@cviebrock
Copy link
Author

See twigphp/Twig#2532 for context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment