PrestaShop:使用smarty添加javascript数组元素
PrestaShop: add javascript array elements using smarty
我正在想办法从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(
'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" ]
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>
相关文章:
- javascript数组元素是否知道其封闭数组
- JavaScript数组元素只不过是数组对象属性
- 在javascript数组元素之间添加换行符
- 从 QML 中的 ListModel 访问 Javascript 数组元素
- 从 C# 访问 JavaScript 数组元素(通过 WebBrowser)
- 将属性添加到 javascript 数组元素
- 通过循环变量引用Javascript数组元素
- 通过JSON对象键访问javascript数组元素
- 访问Javascript数组元素
- PHP 作为 Javascript 数组元素
- PrestaShop:使用smarty添加javascript数组元素
- Javascript数组元素计数
- 在Google Maps API中未定义Javascript数组元素
- 计算JavaScript数组元素的出现次数,并放入一个新的2d数组
- 删除JavaScript数组元素显示未定义
- Javascript数组.元素长度对小于2个元素不起作用
- 访问Javascript数组元素
- Javascript数组元素未定义
- 为什么javascript数组元素不能'
- 为javascript数组元素赋值在循环时不起作用(classic.asp),但在没有循环的情况下也能起作用,为什么