简体   繁体   English

如何在Smarty修饰符函数中分配新变量?

[英]How can I assign a new variable inside of a Smarty modifier function?

I wrote a basic Smarty modifier that emulates JavaScript's push. 我写了一个基本的Smarty修饰符,模仿JavaScript的推送。

function smarty_modifier_push($array, $push){
    if(!isset($array)){
        $array = array($push);
    }elseif(is_array($array)){
        $array[] = $push;
    }
    return $array;
}

Here is my code in my .tpl file 这是我的.tpl文件中的代码

Problems: 
<select name="problems[]" multiple="multiple">
    <option value="">Select Problems</option>
    {foreach from=$problems key=id item=name}
        {$newArray|push:$id}
        <option value="{$id}">{$name}</option>
    {/foreach}
</select>
{$newArray}

Problem: My dropdown consists of about 20 elements so $newArray should have about 20 id's in it but when I check $newArray , it is empty. 问题:我的下拉列表包含大约20个元素,因此$newArray应该包含大约20个id,但是当我检查$newArray ,它为空。 So it seems that it never gets assigned back to the template after the modifier runs. 因此,似乎在修改器运行之后,它永远不会分配回模板。

I know that I can use {assign var=newArray} in my .tpl file beforehand but I'm hoping that there is a way of assigning new variables from within a modifier function. 我知道我可以预先在.tpl文件中使用{assign var=newArray} ,但我希望有一种从修饰符函数中分配新变量的方法。 I also know it's possible from a function plugin because it gets passed the $smarty variable, but I just want to know specifically, How I can make this work using a modifier plugin? 我也知道可以通过函数插件来实现,因为它可以传递$smarty变量,但是我只想特别知道, 如何使用修饰符插件来完成这项工作?

There is some code posted on the SMARTY FORUM that might help you out. SMARTY FORUM上发布了一些代码,可能会对您有所帮助。 Other people have pointed out that it is a way for you to do what you need but its a little complicated and is not guaranteed to work when new updates come out. 其他人指出,这是您执行需要的操作的一种方法,但是它有点复杂,并且不能保证在出现新更新时就可以正常工作。 Hope it helps you out though. 希望它可以帮助您。 Cheers. 干杯。

Try to push "&" before $array variable like that 尝试像这样在$ array变量之前插入“&”

function smarty_modifier_push(& $array, $push){
    if(!isset($array)){
        $array = array($push);
    }elseif(is_array($array)){
        $array[] = $push;
    }
    return $array;
}

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

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