Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested for loop in flask

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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

>Solution :

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 %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading