Flask - Use Python function in Jinja Template
by
Jeremy Canfield |
Updated: June 04 2023
| Flask articles
Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.
- Model -> models.py
- View -> views.py
- Controller -> __init__.py
Typically, your CSS files will be stored in the static directory, something like this.
├── main.py
├── database (directory)
│ ├── example.db
├── my-project (directory)
│ ├── __init__.py
│ ├── views.py
│ ├── models.py
│ ├── templates (directory)
│ │ ├── base.html
│ │ ├── home.html
│ │ ├── results.html
│ └── static (directory)
│ └── custom.css
In your view (views.py in this example), here is how you can create a function that can be used in your HTML files.
@views.context_processor
def utility_processor():
def greeting():
return 'Hello World'
def return_long_month_name(month):
if month == '01':
return 'January'
elif month == '02':
return 'February'
elif month == '03':
return 'March'
elif month == '04':
return 'April'
elif month == '05':
return 'May'
elif month == '06':
return 'June'
elif month == '07':
return 'July'
elif month == '08':
return 'August'
elif month == '09':
return 'September'
elif month == '10':
return 'October'
elif month == '11':
return 'November'
elif month == '12':
return 'December'
else:
return 'Unknown'
return dict(greeting=greeting, return_long_month_name=return_long_month_name)
And here is how you would use these functions in your HTML templates.
<p> {{ greeting() }} </p>
<p> {{ return_long_month_name('01') }} </p>
Did you find this article helpful?
If so, consider buying me a coffee over at