php - How to Pass array in Volt Template to javascript

I'm using Phalcon and Volt template engine .

This index.volt and I'm going to pass an array to JavaScript

<script type="text/javascript" >

 var usersList= {{ array_from_volt }} ;

</javascript>

But it doesn't work .

in PHP we used to do like this But it doesn't work for volt

<script type="text/javascript" >

 var usersList=  <?php echo json_encode(array_from_php); ?>;

</javascript>  

So, How can I Pass an Array to javascript from volt ?

Answer

Solution:

In your PHP code, use setvar to set a variable that Volt can reference.

$this->view->setVar('array_name', $your_array);

If you need the array json encoded, you can:

$this->view->setVar('array_name', json_encode($your_array));

Then in your Volt file, you can set the javascript variable as follows:

<script>
    var usersList = [{{ array_name }}];
</script>

(note syntax not verified... YMMV)

Source