在 Smarty 中,是否有标准函数或简单的方法从数组生成 json,就像 php 中的
json_encode()
那样?
我在Smarty文档中看不到它,想在这里询问。
这应该有效。 @ 使 smarty 对整个数组运行修饰符,否则它会对每个元素执行此操作。
{$myarray|@json_encode}
如果启用了 $escape_html,您将需要使用
nofilter
:
{$myarray|@json_encode nofilter}
虽然
{$myarray|@json_encode}
实际上发出了以 json 编码的数组,但它也会转义特殊字符,使得该数组在 javascript 中无法使用。
为了避免转义特殊字符并能够在 javascript 中使用数组,请使用 nofilter 标志:
{$myarray|@json_encode nofilter}
您必须在 php 代码中使用
json_encode()
,然后使用该值将值分配给 smarty
$smarty->assign()
功能。之后,您必须使用以下命令解析模板文件中的该值
JavaScript。
代码片段:
{literal}
<script>
var json = JSON.parse('{/literal}{$your_json_encoded_array}{literal}');
//another statement
</script>
{/literal}
虽然
{$myarray|@json_encode nofilter}
可以工作,但这里存在一个安全漏洞,因为我们正在进行变量转义。强烈建议不要使用变量转义(通过 nofilter
),因为恶意代码可以轻松显示和执行。
还有另一种方法可以考虑,使用
'javascript'
转义并将 '"'
替换为 "
:
{literal}const my_javascript_array = JSON.parse(`{/literal}{json_encode($myarray)|escape:'javascript'}{literal}`.replaceAll('"', '"'));
这有点复杂,但你会感谢自己学习了这个技巧:)
{literal}
<script type="text/javascript">
<!--
var newVar ={/literal}{$myarray|@json_encode nofilter};{literal}
// -->
</script>
{/literal}
我的解决方案
我一个也不知道。您可以使用 $smarty->assign( ... ) 将 json_encode() 的结果分配给“php 代码”中的 smarty 变量,然后在模板中使用它。
还有一个用于 json_decode() 的 Smarty 扩展。基于此编写自己的相反扩展应该不难。
现在,在 smarty 4.3.4 中,@json_encode 内置修饰符已被弃用。您需要编写自己的修饰符:
$smarty->registerPlugin('modifier', 'json_encode', function($json) {
return json_encode($json, JSON_THROW_ON_ERROR);
});
然后就可以在模板中使用了:
<script type="text/javascript">
// we are setting some variables
// nofilter disables html entity escaping
var variables = {$variables|json_encode nofilter};
</script>
<!-- if you need to write the json_encoded string as html data attribute add |escape:'html' : -->
<script type="text/javascript" data-userinfo="{$variables|json_encode|escape:'html'}" src="..."></script>