简体   繁体   English

如何用smarty生成json?

[英]Howto generate json with smarty?

In Smarty, is there a standard function or an easy way to generate json from an array, as json_encode() does in php?在 Smarty 中,是否有标准函数或从数组生成 json 的简单方法,如json_encode()在 php 中所做的那样?

I could not see it in Smarty documentation, wanted to ask here.我在 Smarty 文档中看不到它,想在这里提问。

This should work.这应该有效。 The @ makes smarty run the modifier against the whole array, otherwise it does it for each element. @ 使 smarty 针对整个数组运行修饰符,否则它会针对每个元素执行此操作。

{$myarray|@json_encode}

If $escape_html is enabled, you will need to use nofilter :如果启用了$escape_html ,您将需要使用nofilter

{$myarray|@json_encode nofilter}

While {$myarray|@json_encode} does in fact emit the array encoded in json, it also escapes special characters, making the array unusable in javascript.虽然{$myarray|@json_encode}实际上确实发出以 json 编码的数组,但它也会转义特殊字符,使数组在 javascript 中无法使用。

To avoid escaping special characters and also be able to use the array in javascript use the nofilter flag:为了避免转义特殊字符并能够在 javascript 中使用数组,请使用 nofilter 标志:

{$myarray|@json_encode nofilter}

You have to use json_encode() in your php code then assign the value to smarty using $smarty->assign() function.您必须在 php 代码中使用json_encode()然后使用$smarty->assign()函数将值分配给 smarty。 After that you have to parse that value in your template file using javascript.之后,您必须使用 javascript 解析模板文件中的该值。

code snippet:代码片段:

{literal}
<script>
var json = JSON.parse('{/literal}{$your_json_encoded_array}{literal}');
//another statement
</script>
{/literal}
{literal}
<script type="text/javascript">
<!--
var newVar ={/literal}{$myarray|@json_encode nofilter};{literal}
// -->
</script>
{/literal}

My solution我的解决方案

I don't know of any.我一个都不知道。 You could assign the json_encode()'s result to a smarty variable in your 'php code' with $smarty->assign( ... ), and then use it in your template.您可以使用 $smarty->assign( ... ) 将 json_encode() 的结果分配给“php 代码”中的一个 smarty 变量,然后在模板中使用它。

Also there is a Smarty extension for json_decode().还有一个用于 json_decode() 的 Smarty扩展 It shouldn't be hard to write your own extension for the opposite based on this.基于此为相反的情况编写自己的扩展应该不难。

While {$myarray|@json_encode nofilter} will work, there is a security hole here since we are doing variable escaping.虽然{$myarray|@json_encode nofilter}可以工作,但这里有一个安全漏洞,因为我们正在做变量转义。 Variable escaping (via nofilter ) is highly discouraged because malicious code can be displayed and executed easily.非常不鼓励变量转义(通过nofilter ),因为恶意代码可以很容易地显示和执行。

There is another approach to consider, using the 'javascript' escaping and replacing '&quot;'还有另一种方法需要考虑,使用'javascript'转义并替换'&quot;' with " :"

{literal}const my_javascript_array = JSON.parse(`{/literal}{json_encode($myarray)|escape:'javascript'}{literal}`.replaceAll('&quot;', '"'));

It is a bit convoluted, but you will thank yourself down the line for learning this trick :)这有点令人费解,但你会感谢自己学习这个技巧:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM