javascriptphpsmartysmarty3

How to pass array from php to javascript using smarty 3?


In php file When I code like this

$names = ["jim", "lucy"];
$smarty->assign('names', $names);

In javascript,

var arr = {$names};

Smarty will parse the {$names} as ...&quot... .

What should I do to avoid this? I want Smarty parse the array as

var arr = ['jim', 'lucy'];


Solution

  • In php:

    $names = ['jim', 'lucy'];
    $smarty->assign('names', $names);
    

    In javascript,

    var arr = {$names|json_encode};
    

    Notice: If you changed your smarty default_modifiers to array('escape:"html"'), use

    var arr = {$names|json_encode nofilter};
    

    to make everything work.

    Good luck.