Flask - (5)

Custom filters

2019-12-29
by cS


We can make custom template filters for stuff to format, check, or modify content.

In the app.py file we can make a filter that takes in a datetime.datetime.now() call and returns back a nicer output.

import datetime

# To register a filter, just add this decorator to a function,

@app.template_filter("report_head")
def report_head(date):
    date = str(date)[:10]
    return "Milky-Way SOCOM Center Admin Panel Date {}".format(date)

We have to feed the template a datetime.datetime.now() to run it through the filter, so just send the date back like this.

@app.route("/", methods=("GET",))
def index():
    date = datetime.datetime.now()
    stuff = {
        "location" : "Uranus",
        "unit" : "NVM-1999",
        "AO" : "Blue Fields",
        "operating_assets" : 13,
        "not_ok" : 0,
    }
    return render_template("home.html", stuff=stuff, date=date)

The home.html file may look like this

{% block content %}
    <!--
        this is how we make use of the filter we just created,
        this should render a div with a message containing the 
        datetime.datetime.now() call, which is a datetime.datetime object.
    -->
    {{ date | report_head }}

    <h3>Drone units status</h3>
    <p> Unit Location {{ stuff.location }} </p>
    <p> Unit Name {{ stuff.unit }} </p>
    <p> Area of Operation {{ stuff.AO }} </p>
    <p> Unit Count {{ stuff.operating_assets }} </p>
    <p> Unit Casualties {{ stuff.not_ok }} </p>
    <style>
        body{ color: white; background: black;}
    </style>
{% endblock %}