简体   繁体   中英

Set twig variable from javaScript

I need to generate url to be able to load some content in html element.

$('#editSchool').click(function () {
            var id = $(this).attr('data-id');

Problem starts here when I try to insert id value for id parameter

            $('#educationDialog').load("{{ path('_education_edit', {'id': id}) }}", function () {
                $('.closeDialog, #person_education_form_cancel').click(function () {
                    $('#addSchool').trigger('click');
                });
            });
        });

Do you have some solution, if this is possible?

you can use FOSJSRouting bundle :

http://symfony.com/doc/current/bundles/FOSJsRoutingBundle/usage.html

With this bundle you can generate routes in javascript

The twig is parsed when the page is rendered, so the id variable in your route declartion is set when the page loads.

The easiest fix is to change your route to accept a nullable parameter for the id, then add the id to the route in your JavaScript. Also, for use in JavaScript, you will need to use the url twig function as it gives an absolute url, path gives a relative url. Ref: What is the difference between 'url' and 'path' in symfony2.3

Example routing.yml;

my_route:
    path:    /foo/bar/{id}
    defaults:   { _controller: AppBundle:Foo:bar, id: null }

Then in your twig;

<script>
var url = '{{ url('my_route') }}'+'/';
var id = $(this).attr('data-id'); 
$('#educationDialog').load(url+id, function () {
    // ...
});
</srcipt>

The problem was very simple. Instead of passing data-id attribute, data-url can be passed.

<span id="editSchool" data-url="{{ path('_education_edit', {'id': id}) }}">  
     Edit School
</>

$('#editSchool').click(function () {
        var url = $(this).data('url');

        $('#educationDialog').load(url, function () {
            $('.closeDialog, #person_education_form_cancel').click(function () {
                $('#addSchool').trigger('click');
            });
        });
    });

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