Reputation: 2962
I'm trying to pass a twig array variable to javascript, but for some reason it keeps stating that the variable does not exist.
My twig:
{% set clients = [] %}
{% for work in works %}
{% set clients = clients|merge([ work.name ]) %}
{% endfor %}
{% set client_array = clients|json_encode|raw %}
When I try and call client array with {{client_array}}
I have no trouble whatsoever, it returns the correct array.
However my problem is when I try to define a javascript variable below in a javascript block on the page to be equal to client_array.
<script>
var clients = '{{ client_array }}';
...
</script>
I keep getting
Variable "client_array" does not exist.
I feel there's some dumb syntax error I'm making here. Can anyone see the problem?
Upvotes: 0
Views: 959
Reputation: 1959
Try Passing Information from Twig to JavaScript
In controller create variable:
public function index(Request $request) {
/* ... */
$clients = array(array("id" => 1, "name" => "test1"), array("id" => 2, "name" => "test2"));
$names = array_map(function ($ar) {
return $ar['name'];
}, $clients);
$twigparms = array("clients" => $names);
return $this->render("YourTemplate/index.html.twig", $twigparms);
}
in Twig use it
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Page Title</title>
<body>
<div class="clients" id="clients" data-names="{{ clients|json_encode|e('html_attr') }}"></div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var clientstmp = document.querySelector('.clients');
var clients = clientstmp.dataset.names;
console.log(clients);
});
</script>
</body>
</html>
Upvotes: 1
Reputation: 2962
ok, so I took a different approach to this and chose to set the variable in the controller and that worked
$clients = [];
foreach ($works as $work) {
$client = $work['name'];
array_push($clients, $client);
}
While comparing the output side by side, they were identical, so my conclusion is that it appears that twig "set" variables don't seem to be recognized outside the block. (don't quote me on this)
Upvotes: 1