简体   繁体   中英

parsing variable from javascript to html twig

I started using html twig in Symfony2 and I got the following problem:

function goEditConflict(){
    $("#go").on("click", function(){
    id = $("#case_number").val();

    windows.location = {{ path("acf_case_conflict_edit", {"id" : id}) }} ;
    });
}

Variable "id" does not exist in ACFCaseBundle:Shared:caseHierachy.js.twig at line 38

I try to redirect page base on the id variable but I got the error that when I try redirect to {{ path("acf_case_conflict_edit", {"id" : id}) }} the variable does not exist.

How can I use a js variable in my twig code?

Your twig will get written before your javascript runs, and as such, it cannot parse the id from the jquery call. In this case, you are better off using javascript to append the id to a dummy route:

acf_case_conflict.yml:

acf_case_conflict_stub:
    pattern:  /
    defaults: { _controller: "Bundle:acf_case_conflict:edit" }

twigged out js:

function goEditConflict(){
    $("#go").on("click", function(){
    id = $("#case_number").val();
    windows.location = {{ path("acf_case_conflict_stub")}}+"/"+id+"/edit";
    });
}

This will write the new js file to have the new location each time the page is rendered.

Use this code

function goEditConflict(){
 $("#go").on("click", function(){
    var url = "{{ path("acf_case_conflict_edit", {"id" : js_id}) }}";

    js_id = $("#case_number").val();
    url = url.replace("id", js_id);
    windows.location = url ;
 });
}

I did the following :

function goEditConflict(){
    $("#go").on("click", function(){
    id = $("#case_number").val();
    {% set var %}
          id
    {% endset %}
    windows.location = {{ path("acf_case_conflict_edit", {"id" : var}) }} ;
    });
}

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