简体   繁体   English

Smarty:在模板中取消设置数组索引

[英]Smarty: unset an array index in template

I would like to do {unset($array['index'])} into a Smarty 3 template.我想将{unset($array['index'])}放入 Smarty 3 模板中。

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 ?也许我应该向 Smarty 开发团队提出功能请求? :) :)

Anyway, how would you do this given the currently available template functions ?无论如何,鉴于当前可用的模板功能,您将如何做到这一点?

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.尽管在模板中执行此操作不是一个好主意,但有时它可能会节省您的时间。

I don't think there's a direct support for this in smarty.我不认为 smarty 对此有直接支持。 You can always do this with smarty's {php} tag, however I would strongly discourage you from doing so.你总是可以用 smarty 的{php}标签来做到这一点,但是我强烈建议你不要这样做。 Logic doesn't belong in a presentation-level template.逻辑不属于演示级模板。

试试这个

{$array.index = null}

Two steps:两个步骤:

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

It work in Smarty3.它适用于 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.我也不明白为什么要取消设置一个 smarty 变量:只要不使用它,它就不会显示。

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

Here 10 is an array index.这里10是一个数组索引。

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但是您可以编写自己的修饰符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.这在 smarty <3 中对我有用,不知道是否仍然有效,因为它们真的把 smarty 搞砸了。

try尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM