我正在尝试找出在 PrestaShop 中从 *.tpl 文件添加数组元素的方法。
我有的是js变量:
var combinations = [];
我需要的是从 *.tpl 文件向该数组添加元素。 我有可用的 $combinations 项目数组、数组、数组数组等,并分配了键 - 所以内爆没有意义。
我正在尝试这样的事情:
{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(
'd21' => '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" ]
编辑2
如果您需要使用 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>
关于javascript - PrestaShop:使用 smarty 添加 javascript 数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25961303/