检索名称由变量组成的Smarty变量的值


Retrieve a value of Smarty variable whose name consists of variables

我有一组php变量数组,它们被分配到SMARTY模板中。以下是php变量:

$smarty = new Smarty;
for ($i = 1; $i <= 3; ++$i) {
  ${'field'.$i} = array('group_rank_edit_' . $i, 'some_data'.$i);
  // Assign variable to the template
  $smarty->assign('field'.$i , ${'field'.$i});
}

因此,有3个数组被分配给模板。现在,在模板中,我在检索值时遇到了困难。假设模板有点像这样:

{{for $i=1 to 3}}
  $().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules: {
           {{$field.{{$i}}.0}}: {
                required: true,
            }
        },
     });
});
{{/for}}

因此,其中一个输出将如下所示:

$().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules: {
          group_rank_edit_1 : {
                required: true,
            }
        },
     });
});

显然,以下格式不会产生预期的输出:

{{$field.{{$i}}.0}}

有什么想法吗?我正在使用Smarty 3 BTW.

非常感谢

您可以将字段存储在一个数组(PHP)中,并使用foreach对其进行迭代(Smarty)。

PHP

$smarty = new Smarty;
$f      = [];                // array will contain data of all 3 fields
for ($i = 1; $i <= 3; ++$i)  // fill array with data
{
    $f[$i] = array('group_rank_edit_' . $i, 'some_data'.$i);
}
$smarty->assign('f' , $f);   // assign the array to smarty

智能

{foreach from=$f key=i item=data}
    {literal}
        $().ready(function() {
            $("#group-ranks-edit-form").validate({
                rules:
    {/literal}
                    {$data.0}:
    {literal}
                    {
                        required: true,
                    }
                },
            });
        });
    {/literal}
{/foreach}

Smarty生成的输出

$().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules:
            group_rank_edit_1:
            {
                required: true,
            }
        },
    });
});
$().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules:
            group_rank_edit_2:
            {
                required: true,
            }
        },
    });
});
$().ready(function() {
    $("#group-ranks-edit-form").validate({
        rules:
            group_rank_edit_3:
            {
                required: true,
            }
        },
    });
});