PrestaShop:使用smarty添加javascript数组元素

PrestaShop: add javascript array elements using smarty

本文关键字:javascript 数组元素 添加 smarty 使用 PrestaShop      更新时间:2023-09-26

我正在想办法从PrestaShop中的*.tpl文件中添加数组元素。

我有js变量:

var combinations = [];

我需要的是从*.tpl文件向这个数组添加元素。我有$combings项目数组、数组、数组数组等,并分配了键,所以内爆没有意义。

我正在尝试类似的东西:

{addJsDef combinations[]=$combinations} but it of course won't work.

由于PS文档比糟糕还要糟糕,我想这只是猜测,但也许有人也遇到过类似的问题。。。

如果我很了解你,如果在PHP中你分配给像这样的Smarty元素:

$smarty->assign('combinations', array (1,2,3,20));

你可以在Smarty:中使用

<script>
    var combinations = [];
    {foreach $combinations as $item}
    combinations.push({$item})
    {/foreach}
    console.log(combinations);
</script>

当我添加console.log(combinations);登录JS控制台时,控制台中有

Array [ 1, 2, 3, 20 ]

因此所有元素都被插入到JavaScript数组中。

如果你有更复杂的PHP数组:

$smarty->assign('combinations', array(
        'a' => 'aval',
        'b' => 'bval',
        'c' => array('c1' => 'c1val', 'c2' => 'c2val'),
        'd' => array(
            'd1' => 'd1val',
            'd2' => array(
                'd2‌​1' => 'd21val',
                'd22'   => 'd22val',
                'd23'   => array('d231', 'd232')
            )
        )
    ));

并且您想要创建可以使用的平面JavaScript数组:

{function jsadd}
    {foreach $data as $item}
        {if not $item|@is_array}
            combinations.push('{$item}')
        {else}
            {jsadd data = $item}
        {/if}
    {/foreach}
{/function}
<script>
    var combinations = [];
    {jsadd data=$combinations}
    console.log(combinations);
</script>

你会得到:

Array [ "aval", "bval", "c1val", "c2val", "d1val", "d21val", "d22val", "d231", "d232" ]

EDIT2

如果你需要使用PHP中的数据在JavaScript中创建多维数组,正如你在评论中解释的那样,你可以使用这个Smarty模板:

{function jsadd keypart=''}
    {foreach $data as $key => $item}
        {if not $item|@is_array}
            {if $keypart eq ''}
                combinations['{$key}'] = '{$item}'
             {else}
                combinations{$keypart}['{$key}'] = '{$item}'
            {/if}
        {else}
            combinations{$keypart}['{$key}'] = [];
            {jsadd data = $item keypart = "`$keypart`['`$key`']" }
        {/if}
    {/foreach}
{/function}
<script>
    var combinations = [];
    {jsadd data=$combinations}
    console.log(combinations['a']);
</script>