for in range no flask template

Asked

Viewed 218 times

0

I’m in doubt, the API I’m getting returns me two data types "ID" and "Title" are several id and title and I wanted to play this on my table in a "for" template. I wanted to know if what I did was right because he doesn’t return anything.

code in flask

from flask import Flask, render_template
import requests
import json

app = Flask(__name__)

def game():
    url = requests.get("https://jsonplaceholder.typicode.com/posts")
    resp = json.loads(url.text)
    return resp

@app.route("/")

def index():
    return render_template("index.html", data = game())



if __name__ == "__main__":

    app.run()

Is the template:

  <!doctype html>
<html>
<head>
    <title>Minha pagina</title>
    <meta charset="utf-8" />
</head>
<body>
    <h1>Teste de API</h1>
    <br>

    <table border = "1">
        <tr>
            <td align= middle width=100 bgcolor= #DAA520> ID </td>
            <td align= middle width=100 bgcolor= #DAA520> TITLE</td>
        </tr>
        <tr>
        {% for i in range(3) %}
            <td align= middle width=150>{{resp[i] ["id"]}}</td>
            <td align= middle width=150>{{resp[i]["title"]}}</td>
        {% endfor %}

        </tr>

    </table>

</body>


</html>

2 answers

0

You don’t get data return in your template because you’re using the wrong variable name. Instead of resp, you must use data, the same name you used to pass the data in the function return index.

A suggestion: For the sake of readability, usually when I need to use some kind of iteration in templates, I do this explicitly, that is, considering that data probably is a list of dictionaries, I would write your code as follows:

{% for element in data %}
    <td>{{ element["id"] }}</td>
    <td>{{ element["title"] }}</td>
{% endfor %}

In my experience, it makes it much easier to write the code as readable as possible. After some time without seeing the unreadable code, when writing about it again, it doesn’t seem like you wrote it yourself that is so confusing that it is trying to understand your own code again, and it consumes a lot of time.

I also recommend adding attributes to HTML elements using CSS for style (align="Middle"...) or Javascript for any other attribute you want.

0

respis not defined, is data

{% for i in range(3) %}
    <td align= middle width=150>{{data[i] ["id"]}}</td>
    <td align= middle width=150>{{data[i]["title"]}}</td>
{% endfor %}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.