简体   繁体   中英

How to pass data to jinja templet

I might be tired after long hours of punching on keyboard but I'm currently unable to move any further. Here is the code:

        elif request.form["submit"] == "blah":
        cursor.execute('''SELECT * FROM "Table_x"''')
        results = cursor.fetchall()
        for record in cursor:
            results.append(record)
        return "Showing all:" + str(results) + render_template("index.html")

Based on the above, output on rendered template gives me a nasty looking list of tuples.

[(1, 'Dummy1', 'dummy1', 1), (2, 'Dummy2', 'dummy2', 2), (3, 'Dummy3', 'dummy3', 3)] 

How can I change return or results variable (or both) so that each tuple in the list would print in separate line ?

The problem is how you are passing the data to your template, using render_template from the documentation:

Renders a template from the template folder with the given context.

Parameters: template_name_or_list – the name of the template to be rendered, or an iterable with template names the first one existing will be rendered context – the variables that should be available in the context of the template.

The context is nothing more than the variables you want to pass as keywords arguments. Follow an example, first the python file app.py :

#!/usr/bin/python3

from flask import Flask, render_template

app = Flask(__name__)


@app.route("/tuple")
def jpg_to_pdf():
    results = [(1, 'Dummy1', 'dummy1', 1), (2, 'Dummy2', 'dummy2', 2), (3, 'Dummy3', 'dummy3', 3)]
    return render_template('index.html', data=results)

and the Jinja template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuple</title>
</head>
<body>
<table style="width: 100%">
{% for element in data %}
 <tr>
    <th>{{ element[0] }}</th>
    <th>{{ element[1] }}</th>
    <th>{{ element[2] }}</th>
    <th>{{ element[3] }}</th>
  </tr>
{% endfor %}
</table>
</body>
</html>

Those files combined render the following html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuple</title>
</head>
<body>
<table style="width: 100%">

 <tr>
    <th>1</th>
    <th>Dummy1</th>
    <th>dummy1</th>
    <th>1</th>
  </tr>

 <tr>
    <th>2</th>
    <th>Dummy2</th>
    <th>dummy2</th>
    <th>2</th>
  </tr>

 <tr>
    <th>3</th>
    <th>Dummy3</th>
    <th>dummy3</th>
    <th>3</th>
  </tr>

</table>
</body>
</html>

You can find more about rendering templateshere .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM