I pass my template an array of strings which I would like to convert to a jaavascript array:
Controller file (php):
$myVar = array('a','b','c');
Desired html:
var myVar = ["a","b","c"];
I try the following code (twig):
var myVar = ["{{ myVar | join('","') }}"];
But the twig generator converts the quotation marks to html entities and this is the result:
var myVar = ["a","b","c"];
Some idea?
You need to apply the raw
filter:
var myVar = ["{{ myVar | join('","') | raw }}"];
Maerlyn's answer will work, however the drawback with it is that the values in the myVar
array will be outputted raw too, which, depending on the origin of that variable, could lead to vulnerabilities in your website, such as XSS.
I found two ways to do this while maintaining the escaping on the array values. The first is using a loop with an if
statement to check whether it's the last iteration to determine whether we need to output the "glue" used in the join or not:
var myVar = [{% for val in myVar %}"{{ val }}"{% if loop.last == false %},{% endif %}{% endfor %}]
The second way is to let PHP your PHP handle everything, including the escaping, and then output the raw string in Twig:
$arr = array_map(
function($value) {
return '"' . htmlspecialchars($value, ENT_QUOTES, 'UTF-8') . '"';
},
$arr
);
$myVar = '[' . implode(',', $arr) . ']';
Then pass the $myVar
variable to your view, and then you can just do:
{{ myVar|raw }}