Search code examples
pythonflaskjinja2

Count number of entries in table then display with jinja inside html


I have a flask application that takes in data from a form and saves it to a table built with SQLAlchemy. I am building a dashboard that will display little snippets of information like the total entries in the table for example. I ran the code below and have no errors but nothing displays where I used the jinja within the html.

views.py

#equipment home page
@equipment_blueprint.route('/', methods=['GET','POST'])
def equipment_home():
    #total equipment card
    total_equipment = db.session.query(EquipmentInfo).count()

    return render_template('equipment_base.html')

The total_equipment variable is what I am trying to use to count the entries in the EquipmentInfo table.

html

<!-- first bootstrap card -->
<div class="card text-white bg-dark mb-3" style="max-width: 18rem;">
<div class="card-header">Header</div>
<div class="card-body">
    <h5 class="card-title">Dark card title {{ total_equipment }} </h5>
    <p class="card-text">Some quick example text to build on the card title 
    and make up the bulk of the card's content.</p>
</div>
</div>

I tried inserting the {{ total_equipment }} into the html. Is there another way to do this that would work? I just entered it into the title for testing purposes to see if this works.


Solution

  • You need to provide the names and values of template variables to render_template, like this:

    return render_template('equipment_base.html', total_equipment=total_equipment)
    

    Refer to the docs here.