Passing SQL table column names to jinja2 (Flask) view

Solved issue: how to insert sql table column headers into template in Flask.

First, I will create a model – using sqlalchemy, I create a class that inherits from the model class. The attributes of this class correspond to the column names of the database table. An example of a Contract class declaration would look like this:

class Contract(db.Model):

Then in the controller I pass the column names from the model created in this way to the template:

@bp.route('/contract', methods=['GET'])
def contracts(page=1, per_page=5):
    columns = = [m.key for m in Contract.__table__.columns]
   # some other code here, not important for this example
    return render_template('contracts.html', title='Contracts', header=columns)

Data from the header passed to the template can be e.g. placed in the header of the html table:

        {% for item in header %}
            <th class="is-info">
                {{ item }}
        {% endfor %}

Leave a Reply

Your email address will not be published.

WC Captcha 83 − = 73