Home > Software engineering >  Nested for loop in flask
Nested for loop in flask

Time:06-10

Im new to flask and trying to create a simple trivia application.. Im having trouble with the nested jinja for loop inside the index.html It loops through the answers ok but not the questions, for eg: same question is rendered in the browser for each line, the answers are ok... Hoping to understand if I have written the nested loop correctly in the index.html file?

app.py

from flask import Flask, render_template
from questionData import *

app = Flask(__name__)

@app.route('/')
def index():
    data = getQuestionData()
    questions  = saveQuestions(data)
    answers = getAnswers(data)
    return render_template('index.html',questions = questions, answers = answers)

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Questions Application</title>
</head>

<body>
    <div>
        {% for question in questions %}
        {% for answer in answers %}
        <h2>{{question}}</h2>
        <h3>{{answer}}</h3>
        {% endfor %}
        {% endfor %}
    </div>
</body>

</html>

.py file

import requests
import json


def getQuestionData():
    response = requests.get('https://opentdb.com/api.php?amount=50&category=9&difficulty=easy&type=multiple')
    data = json.loads(response.text)
    return data


def saveQuestions(data):
    questions = []
    for result in data['results']:
        question = result['question']
        questions.append(question)
    return questions
    

def getAnswers(data):
    answers = []
    for result in data['results']:
        answer = result['correct_answer']
        answers.append(answer)
    return answers

Browser Render

CodePudding user response:

If you only want the answer for each question, you don't need two lists.

data = getQuestionData()
to_render = list()
for r in data.get('results', []):
    to_render.append({ 
        'question': r['question'],
        'answer': r['correct_answer']
    })

return render_template('index.html', data=to_render)
{% for d in data %}
<h2>{{d['question']}}</h2>
<h3>{{d['answer']}}</h3>
{% endfor %}
  • Related