2012-06-27 118 views
2

我在我的django應用程序中有一個二維數組,我需要傳遞給html模板。二維數組Django

如何讓HTML處理二維數組?

{% 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 %} 

我得到錯誤:

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

回答

9
{% 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 %} 
0

Django的只是沒有傳遞多維數組到模板的設置預方式。

最好的解決辦法是,以各列,手動像這樣分開......(「I」對應於每一行中最後輸出)在你的模板

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) 

然後

{% 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 %}