php 如何用smarty生成json?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1285514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Howto generate json with smarty?
提问by Sinan
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 文档中看不到它,想在这里提问。
回答by Tom Haigh
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_htmlis enabled, you will need to use nofilter:
如果启用了$escape_html,您将需要使用nofilter:
{$myarray|@json_encode nofilter}
回答by m_katsifarakis
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}
回答by Kanagu
You have to use json_encode()in your php code then assign the value to smarty using
$smarty->assign()function. After that you have to parse that value in your template file using
javascript.
您必须json_encode()在 php 代码中使用,然后使用$smarty->assign()函数将值分配给 smarty
。之后,您必须使用 javascript 解析模板文件中的该值。
code snippet:
代码片段:
{literal}
<script>
var json = JSON.parse('{/literal}{$your_json_encoded_array}{literal}');
//another statement
</script>
{/literal}
回答by Sarath E
{literal}
<script type="text/javascript">
<!--
var newVar ={/literal}{$myarray|@json_encode nofilter};{literal}
// -->
</script>
{/literal}
My solution
我的解决方案
回答by Zed
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 extensionfor json_decode(). It shouldn't be hard to write your own extension for the opposite based on this.
还有一个用于 json_decode()的 Smarty扩展。基于此为相反的情况编写自己的扩展应该不难。

