开发者

Smarty: unset an array index in template

开发者 https://www.devze.com 2023-04-06 07:35 出处:网络
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.

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 curren开发者_如何学JAVAtly available template functions ?


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.


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.


try this

{$array.index = null}


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}


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.


I think, that you shouldn't want this, 'cause all logic must be in code not in templates.

But you can write your own modifier http://www.smarty.net/docs/en/plugins.modifiers.tpl


you don't you overwrite the value?

{assign var="array" value=array()}
{$array['index']='1'}
{$array['index2']='2'}
{$array['index']=''}
{$array|print_r}

this worked for me in smarty <3, don't know if still works as they really messed up smarty.


{$array=$links.lists|array_diff_key:(['10']|array_flip)}
{$array|print_r}

Here 10 is an array index.


try

{assign var=$array.index value=null)}

0

精彩评论

暂无评论...
验证码 换一张
取 消