Howto generate json with smarty? Howto generate json with smarty? json json

Howto generate json with smarty?


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}


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}


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 usingjavascript.

code snippet:

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