Twig: Add a without filter, which excludes elements from an array

Created on 24 Apr 2016  Â·  2Comments  Â·  Source: twigphp/Twig

Let's assume you have an array with 3 elements, footer, header and body and you want to exclude one of them.

What about introducing a filter which works like that:

<strong>No author:</strong> {{ quote | without('author') }}.

The implementation could be something like:

  if ($element instanceof ArrayAccess) {
    $filtered_element = clone $element;
  }
  else {
    $filtered_element = $element;
  }
  $args = func_get_args();
  unset($args[0]);
  foreach ($args as $arg) {
    if (isset($filtered_element[$arg])) {
      unset($filtered_element[$arg]);
    }
  }
  return $filtered_element;

Any thoughts about it?

Most helpful comment

Actually, you are returning an array which will be converted to string by {{ }} so this example looks broken.

Beside that, I agree Twig core misses a way to unset values. Also with keyword is already used and without in this context could be misleading.

What about:

{% do some_array|unset_keys('key1', 'key2') %}
{# or #}
{% set filtered = some_array|unset_keys('key') %}

Note that you can already use an if in for loops which allows:

{% for key, value in some_array if key not in ['key1', 'key2'] %}
{# ... #}

All 2 comments

Actually, you are returning an array which will be converted to string by {{ }} so this example looks broken.

Beside that, I agree Twig core misses a way to unset values. Also with keyword is already used and without in this context could be misleading.

What about:

{% do some_array|unset_keys('key1', 'key2') %}
{# or #}
{% set filtered = some_array|unset_keys('key') %}

Note that you can already use an if in for loops which allows:

{% for key, value in some_array if key not in ['key1', 'key2'] %}
{# ... #}

I'm closing this issue as this ticket did not get much traction and I'm not a big fan of easing manipulating variables in the templates (unset_keys).

Was this page helpful?
0 / 5 - 0 ratings