Howto generate json with smarty?

橙三吉。 提交于 2019-12-17 16:16:36

问题


In Smarty, is there a standard function or an easy way to generate json from an array, as json_encode() does in php? Actually It seems there is not in smarty documentation but wanted to ask anyways.

Thanks, Sinan.


回答1:


This should work. The @ makes smarty run the modifier against the whole array, otherwise it does it for each element.

{$myarray|@json_encode}

If $escape_html is enabled, you will need to use nofilter:

{$myarray|@json_encode nofilter}



回答2:


While {$myarray|@json_encode} does in fact emit the array encoded in json, it also escapes special characters, making the array unusable in javascript.

To avoid escaping special characters and also be able to use the array in javascript use the nofilter flag:

{$myarray|@json_encode nofilter}



回答3:


You have to use json_encode() in ur php code then assign the value to smarty using $smarty->assign() function. After that u have to parse that value in ur template file using javascript.

code snippet:

{literal}
<script>
var json = JSON.parse('{/literal}{$urarray}{literal}');
//another statments
</script>
{/literal}



回答4:


{literal}
<script type="text/javascript">
<!--
var newVar ={/literal}{$myarray|@json_encode nofilter};{literal}
// -->
</script>
{/literal}

My solution




回答5:


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.

Also there is a Smarty extension for json_decode(). It shouldn't be hard to write your own extension for the opposite based on this.



来源:https://stackoverflow.com/questions/1285514/howto-generate-json-with-smarty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!