简体   繁体   English

从javaScript设置树枝变量

[英]Set twig variable from javaScript

I need to generate url to be able to load some content in html element. 我需要生成url才能加载html元素中的某些内容。

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

Problem starts here when I try to insert id value for id parameter 当我尝试为id参数插入id值时,问题就从这里开始

            $('#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 : 您可以使用FOSJSRouting捆绑包:

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

With this bundle you can generate routes in javascript 使用此捆绑包,您可以使用javascript生成路线

The twig is parsed when the page is rendered, so the id variable in your route declartion is set when the page loads. 呈现页面时将解析树枝,因此在路由声明中设置页面加载时的id变量。

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. 最简单的解决方法是将路由更改为接受ID的可为空参数,然后将ID添加到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. 另外,要在JavaScript中使用,您将需要使用url树枝函数,因为它提供了绝对URL,路径提供了相对URL。 Ref: What is the difference between 'url' and 'path' in symfony2.3 参考: symfony2.3中的“ url”和“ path”有什么区别

Example routing.yml; 示例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. 除了传递data-id属性,还可以传递data-url。

<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');
            });
        });
    });

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

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