Book Image

Flask Framework Cookbook

By : Shalabh Aggarwal
Book Image

Flask Framework Cookbook

By: Shalabh Aggarwal

Overview of this book

Table of Contents (19 chapters)
Flask Framework Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a custom Jinja2 filter


After looking at the previous recipe, experienced developers might think that it was stupid to use a context processor to create a descriptive product name. We can simply write a filter to get the same result; this will make things much cleaner. A filter can be written to display the descriptive name of the product as shown here:

@product_blueprint.template_filter('full_name')
def full_name_filter(product):
    return '{0} / {1}'.format(product['category'], product['name'])

This can be used as follows:

{{ product|full_name }}

The preceding code will yield a similar result as it did in the previous recipe.

How to do it…

To take things to a higher level, let's create a filter to format the currency based on the current local language:

import ccy
from flask import request

@app.template_filter('format_currency')
def format_currency_filter(amount):
    currency_code = ccy.countryccy(request.accept_languages.best[-2:])
    return '{0} {1}'.format(currency_code, amount...