0

I am trying to make a quizz using Symfony 4. I pass an array of Questions to my template, I tried to make a function i call when the user clicks on an answer, to load the next question.

here is what i tried :

function nextQuestion(){
                {% set i = i+1 %}
                var qst = document.getElementById("question");
                var ans1 =  document.getElementById("answer1");
                var ans2 =  document.getElementById("answer2");
                var ans3 =  document.getElementById("answer3");
                var ans4 =  document.getElementById("answer4");
                qst.innerHTML = "<p>{{qsts[i].getText}}</p>";
                ans1.innerHTML = "<p>{{qsts[i].getAnswers[0]}}</p>";
                ans2.innerHTML = "<p>{{qsts[i].getAnswers[1]}}</p>";
                ans3.innerHTML = "<p>{{qsts[i].getAnswers[2]}}</p>";
                ans4.innerHTML = "<p>{{qsts[i].getAnswers[3]}}</p>";
            }

the variable i is initialized outside the function, the problem is in {% set i = i+1 %}, it only works once then stops incrementing the value i.

i also tried making a javascript variable instead of a twig variable but i couldn't pass it to the twig array with the questions.

So how to properly do something like this ? And would learning a front end framework prevent this kind of difficulties ?

Thank you.

  • 1
    [Convert](https://stackoverflow.com/questions/13928729/use-javascript-to-access-a-variable-passed-through-twig) your `twig` variable to a javascript one. – DarkBee Mar 11 '20 at 05:39
  • 1
    The twig contents are rendered on the server side is - not on the client side as you seem to assume here. Meaning that this kind of code will always display the same question and answers (there literally is no other question/answers available on the client side with this code). If you want to switch between the questions & answers on the client side, you will need to store all the questions and answers in javascript or html from where the javascript can then access these on the client side. – ejuhjav Mar 11 '20 at 08:02

0 Answers0