【问题标题】:Smarty modifer/plugin to get a labels from an arraySmarty modifer/plugin 从数组中获取标签
【发布时间】:2012-09-21 20:53:48
【问题描述】:

这是我从 CMS 发送到 Smarty 的示例数组。

[field] => Array
(
    [value] => 19
    [options] => Array
        (
            [labels] => Array
                (
                    [0] => --- Select ---
                    [1] => John
                    [2] => Mark
                    [3] => Luke
                    [4] => Philip
                )

            [values] => Array
                (
                    [0] => 
                    [1] => 15
                    [2] => 1
                    [3] => 19
                    [4] => 17
                )

        )

所以我通常会写{$field.value}{html_options values=$field.options.values output=$field.options.labels selected=$field.value}

我的问题是如何轻松地从值中获取标签。我试过这个:{$field.options.labels[$field.value]} 但后来意识到这只是要获取数组的索引而不是值。

我知道您可以在 {foreach/if} 中执行此操作,但这会在模板中变得混乱。有没有办法为此编写插件?

【问题讨论】:

  • 我不确定,但这样的事情可以工作{html_options values=array_combine(array_values($field.options.values),array_values($field.options.labels))}

标签: php smarty smarty3


【解决方案1】:

如果没有 foreach 循环,它可以在单行中完成:

{$field.options.labels[$field.value|array_search:$field.options.values]}

或修饰符:

function extractLabel($field){
    $idx = array_search($field['value'], $field['options']['values']);
    if($idx !== FALSE && isset($field['options']['labels'][$idx])){
        return $field['options']['labels'][$idx];       
    }
}

$smarty->registerPlugin('modifier', 'extractLabel', 'extractLabel');

tpl:

{$field|extractLabel}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多