Twig : Unset element from array

You can also use the filter pipe like this:

{% set arr = arr | filter((v, k) => k != '99') %}

You can extend twig to do this

<?php
    class Project_Twig_Extension extends \Twig\Extension\AbstractExtension {

    public function getFunctions(){
        return [
            new \Twig\TwigFunction('unset', [$this, 'unset'], [ 'needs_context' => true, ]),
        ];
    }
    /**
    * $context is a special array which hold all know variables inside 
    * If $key is not defined unset the whole variable inside context
    * If $key is set test if $context[$variable] is defined if so unset $key inside multidimensional array
    **/
    public function unset(&$context, $variable, $key = null) {
        if ($key === null) unset($context[$variable]);
        else{
            if (isset($context[$variable])) unset($context[$variable][$key]);
        }
    }
}

Usage inside twig:

<h1>Unset</h1>

{% set foo = 'bar' %}
{% set bar = { 'foo' : 'bar', } %}

<h2>Before</h2>
<table>
    <tr>
        <td>foo</td><td>{{ foo | default('not applicable') }}</td>
    </tr>
    <tr>
        <td>bar.foo</td><td>{{ bar.foo | default('not applicable') }}</td>
    </tr>
</table>

{% do unset('foo') %}
{% do unset('bar', 'foo') %}

<h2>After</h2>
<table>
    <tr>
        <td>foo</td><td>{{ foo | default('not applicable') }}</td>
    </tr>
    <tr>
        <td>bar.foo</td><td>{{ bar.foo | default('not applicable') }}</td>
    </tr>
</table>

output

Before
|------------------------------|------------------------------|
| foo                          | bar                          |
| bar.foo                      | bar                          |
|------------------------------|------------------------------|


After
|------------------------------|------------------------------|
| foo                          | not applicable               |
| bar.foo                      | not applicable               |
|------------------------------|------------------------------|

Tags:

Twig