Smarty: unset an array index in template

19,120

Solution 1

I don't think there's a direct support for this in smarty. You can always do this with smarty's {php} tag, however I would strongly discourage you from doing so. Logic doesn't belong in a presentation-level template.

Solution 2

There is a way though :-)

{$array=$array|array_diff_key:(['index']|array_flip)}

Even though it is not a good idea to do it in templates, sometimes it might save you time.

Solution 3

try this

{$array.index = null}

Solution 4

Two steps:

{$array.index = null}
{$array = $array|array_filter}

It work in Smarty3.

Example with a dynamic index:

{foreach $array as $item}
    {if $item.foo == 'bar'}
        <h1>{$item.text nofilter}</h1>
        {* unset item from array *}
        {$array[$item@key] = null}
        {$array = $array|array_filter}
        {break}
    {/if}
{/foreach}

{if $array}
    <ul>
    {foreach $array as $item}
        <li>{$item.text nofilter}</li>
    {/foreach}
    </ul>
{/if}

Solution 5

The main idea behind a template engine is that you can do all the loading, logic, unsetting etc. before you parse the view. With that being said you shouldn't be unsetting data in your template, and I'm pretty sure they will not implement that feature request.

I also don't get it why you'd want to unset a smarty variable: just don't use it and it won't get displayed.

Share:
19,120

Related videos on Youtube

Frosty Z
Author by

Frosty Z

https://www.linkedin.com/in/maxime-pacary

Updated on June 27, 2022

Comments

  • Frosty Z
    Frosty Z almost 2 years

    I would like to do {unset($array['index'])} into a Smarty 3 template.

    Is such a syntax (or similar) supported ? After Googling and doc reading I can't find something satisfying.

    Maybe I should ask for a feature request to Smarty dev team ? :)

    Anyway, how would you do this given the currently available template functions ?

  • Frosty Z
    Frosty Z about 12 years
    Thanks for the idea, but unfortunately it doesn't do exactly what I want: starting with Array ( [a] => 1 [b] => 2 ), after doing {$array.a = null}, I get Array ( [a] => [b] => 2 ) instead of Array ( [b] => 2 )