Faery
Faery

Reputation: 4650

Include template file with different variable value on click - Symfony2/Twig

I'm quite noob when it comes to communicating between js files, controllers, templates and at all when in comes to js and ajax.

I have different links like this:

<a class="details" data-index ={{i}}> Link 1 </a>

but on click they do not load another page, but instead open a mini page, which should have different variable for each link.

I want to do something like this:

$('.details').on('click', function(){
        var index = $(this).data('index');
        {% include 'MyBundle::information.html.twig' with {'var':index} %}
});

but in this way .js won't give the index variable to twig and I get error that index is not defined :(

How to fix this? This don't need to go through controller. Changing the 'var' value does the job.

Upvotes: 1

Views: 1914

Answers (1)

d0001
d0001

Reputation: 2190

Best way to do this is using FOSJsRoutingBundle, if for some reason you do not want to use that bundle you might do something like this:

$('#details').on('click', function(){
    var index = $(this).data('index');

    var $whereToLoadContent = $("#divid") ; //where you want to load data
    //__index__ is just a placeholder
    var routeWithPlaceHolder= "{{ path('route_name',{'var':'_index_'}) }}" ; 
    var routeToLoad = routeWithPlaceHolder.replace("_index_",index) ;


    $whereToLoadContent.load(routeToLoad) ;


});

Not sure if syntax is correct but hopefully you get the idea. Again I recommend you use FOSJsRoutingBundle if you will be doing this a lot.

Upvotes: 2

Related Questions