How to pass javascript variables values from twig to controller using href path in Symfony2?

余生长醉 提交于 2019-12-23 05:29:08

问题


I would like to know how to pass javascript variables values from twig to controller using href path in Symfony2. this is my code:

 <html>
<head>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
    <script>
        var a = "hello";
        var b = "hi";
        var c = $('<a href="{{ path('ikproj_groupe_homepagegroupe1', {'id': a, 'num': b}) }}">send data</a>');
        $('body').append(c);
    </script>    
</body>
</html>

The problem is that it displays this message: Variable "a" does not exist . So, my question is: what is the correct code to do that?


回答1:


You need to set a twig variable. Ex:

<script>
    {% set a = 'hello' %}
    {% set b = 'hi' %}
    var c = $('<a href="{{ path('ikproj_groupe_homepagegroupe1', {'id': a, 'num': b}) }}">send data</a>');
    $('body').append(c);
</script> 



回答2:


I find the easiest approach to this is to set the path in the original template using an href (or possible a data) attribute like..

<a href="{{ path('route_name', {'id': a }) }}" 
            class="some-specific-class">Click</a>

Or using a data attribute..

<a href="#" data-href="{{ path('route_name', {'id': a }) }}" 
            class="some-specific-class">Click</a>

And then in the javascript use..

$('a.some-specific-class').on('click', function(e) {
    e.preventDefault();

    var href = $(this).attr('href');
    .. or
    var href = $(this).data('href');

    .. do things with href
});

Alternatively you could you the FOSJSRoutingBundle and pass the id in a data attribute and generate the route from that using..

$('a.something').on('click', function(e) {
    e.preventDefault();

    var id = $(this).data('id'),
        url = Routing.generate('rout_name', {'id': id });

    .. do stuff with url
});


来源:https://stackoverflow.com/questions/24673560/how-to-pass-javascript-variables-values-from-twig-to-controller-using-href-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!