简体   繁体   中英

use twig variable in JS

(Hey!) I try to use a twig variable in my JS file, I tried the way mentionned here but in my case, it doesn't works.

{% for property_name, property_rent in property %}
            <tr>
                <td>
                    {{ property_name }}
                </td>
                <td>
                    {{ property_rent }} €
                </td>
            </tr>
        {% endfor %}

and this JS :

let property = "{{ property }}";
console.log(property);

return {{ property }} instead of an array

Of course I tried with simple and double quotes. Does anyone have any idea ?

你应该在你的变量中使用toArray函数并调用:

app_user = {{ app.user.toArray|json_encode() }};

Did you try something like this?

let property = {{ property }}

Update

Let's try a Symfony way :

Twig :

<div class="js-user" data-user="{{ app.user }}">
</div>

JavaScript:

document.addEventListener('DOMContentLoaded', function() {
    var userBlock = document.querySelector('.js-user');
    var user = userBlock.dataset.user;

    // or with jQuery
    //var user = $('.js-user').data('user');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM