2

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?

4
  • 1
    This error is about twig variable named id. Please check whether such variable is passed to twig template in which you are trying to use it. Commented Apr 17, 2013 at 14:40
  • 3
    are you trying to use a javascript variable in a twig template function? Commented Apr 17, 2013 at 14:54
  • This bundle might help you to generate urls in JS code github.com/FriendsOfSymfony/FOSJsRoutingBundle Commented Apr 17, 2013 at 14:59
  • Yes I try to use a javascript variable in a twig template function. It may sound funny but I really get start with Symfony and I am not sure how js and twig work together. Commented Apr 17, 2013 at 16:25

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Either of the two functions below which use a parameterized twig path function are better than my answer.
3

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

Comments

0

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

1 Comment

Here If you store id into var, it store id into variable var not value of id variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.