2

I have a two-dimension array in my django app which I need to pass to html template.

How I can make HTML handle two-dimensional array?

 {% block content %}

  <h2>Survey</h2>
      <form>

    {% for q in question %}   
          <p>{{q[0]}}</p>
          <p>{{q[1]}}</p>
    {% endfor %}
     <input type="submit" value="submit">
     </form>

{% endblock %}

I got error:

    Could not parse the remainder: '[0]' from 'q[0]'

2 Answers 2

12
{% block content %}

  <h2>Survey</h2>
      <form>

    {% for q in question %}   
          <p>{{q.0}}</p>
          <p>{{q.1}}</p>
    {% endfor %}
     <input type="submit" value="submit">
     </form>

{% endblock %}
Sign up to request clarification or add additional context in comments.

Comments

0

Django just doesn't have a pre-setup way for passing multi-dimensional arrays to templates.

The best work-around is to separate the columns out manually like so... ("i" corresponds to each row in final output)

data = {}    
for i, question_answer in enumerate(question_answer_pairs):
    data[i]= {
        'question':question_answer.question,
        'answer':question_answer.answer
    }
return render(request, 'survey.html', data)

Then in your template

{% block content %}

  <h2>Survey</h2>
      <form>

    {% for key,value in data.items %}   
          <p>{{value.question}}</p>
          <p>{{value.answer}}</p>
    {% endfor %}
     <input type="submit" value="submit">
     </form>

{% endblock %}

Comments

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.