简体   繁体   English

单击包含具有不同变量值的模板文件-Symfony2 / Twig

[英]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. 当涉及到js文件,控制器,模板之间的通信时,以及涉及到js和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 :( 但是以这种方式.js不会将索引变量提供给twig,并且我得到未定义索引的错误:(

How to fix this? 如何解决这个问题? This don't need to go through controller. 这不需要通过控制器。 Changing the 'var' value does the job. 改变'var'值就可以了。

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: 最好的方法是使用FOSJsRoutingBundle ,如果由于某种原因您不想使用该捆绑包,则可以执行以下操作:

$('#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. 再次,我建议您使用FOSJsRoutingBundle,如果您会经常这样做的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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