Reader small image

You're reading from  Flask Framework Cookbook. - Second Edition

Product typeBook
Published inJul 2019
Reading LevelIntermediate
Publisher
ISBN-139781789951295
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Shalabh Aggarwal
Shalabh Aggarwal
author image
Shalabh Aggarwal

Shalabh Aggarwal has more than 13 years' experience in developing and managing enterprise systems, as well as web and mobile applications for small-to large-scale industries. He started his career working on Python, and although he now works on multiple technologies, he remains a Python developer at heart. He is passionate about open source technologies and writes highly readable and quality code. He is a seasoned engineering leader who loves building engineering teams and products from scratch across multiple domains while leveraging different technologies. He is also active in voluntary training for engineering students on non-conventional and open source topics. When not working with full-time assignments, he consults for start-ups on leveraging different technologies. When not writing code, he writes technical and non-technical literature, which is published across multiple blogs.
Read more about Shalabh Aggarwal

Right arrow

Templating with Jinja2

This chapter will cover the basics of Jinja2 templating from the perspective of Flask; we will also learn how to make applications with modular and extensible templates.

In Flask, we can write a complete web application without the need for third-party templating engine. For example, have a look at the following code; this is a standalone, simple Hello World application with a bit of HTML styling included:

from flask import Flask 
app = Flask(__name__) 
 
@app.route('/') 
@app.route('/hello') 
@app.route('/hello/<user>') 
def hello_world(user=None): 
    user = user or 'Shalabh' 
    return ''' 
<html> 
    <head> 
      <title>Flask Framework Cookbook</title> 
 
    </head> 
      <body> 
        <h1>Hello %s!</h1> 
        <p>Welcome to the...

Implementing block composition and layout inheritance

Usually, any web application will have a number of web pages that are different to each other. However, code blocks such as headers and footers will appear the same on almost all pages throughout the site; likewise, the menu will remain the same. In fact, it is usually just the center container block that changes. For this, Jinja2 provides a great way of ensuring inheritance among templates.

With this in mind, it's good practice to have a base template where the basic layout of the site, along with the header and footer, can be structured.

Getting ready

In this recipe, we will try to create a small application where we will have a home page and a product page (such...

Creating a custom context processor

Sometimes, we might want to calculate or process a value directly in templates. Jinja2 maintains the notion that the processing of logic should be handled in views and not in templates, and so keeps templates clean. A context processor becomes a handy tool in this case. With a context processor, we can pass our values to a method, which will then be processed in a Python method, and our resultant value will be returned. This is done by simply adding a function to the template context, thanks to Python allowing its users to pass functions like any other object. In this recipe, we'll see how to write a custom context processor.

How to do it...

To write a custom context processor, follow...

Creating a custom Jinja2 filter

After looking at the previous recipe, experienced developers might wonder why we used a context processor for the purpose of creating a well-formatted product name. Well, we can also write a filter for the same purpose, which will make things much cleaner. A filter can be written to display the descriptive name of a product, as shown in the following example:

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

This can also be used as follows:

{{ product|full_name }} 

The preceding code will yield a similar result as in the previous recipe. Moving on, let's now take things to a higher level by using external libraries to format currency.

...

Creating a custom macro for forms

Macros allow us to write reusable pieces of HTML blocks. They are analogous to functions in regular programming languages. We can pass arguments to macros as we do to functions in Python, and we can then use them to process an HTML block. Macros can be called any number of times, and the output will vary as per the logic inside them. In this recipe, let's understand how to write a macro in Jinja2.

Getting ready

Macros in Jinja2 are a very common topic and have a lot of use cases. Here, we will just take a look at how a macro can be created and then used after importing it.

How to do it...

...

Advanced date and time formatting

Date and time formatting is a painful thing to handle in web applications. Such formatting in Python, using the datetime library, often increases overhead and is pretty complex when it comes to the correct handling of time zones. We should standardize timestamps to UTC when they are stored in the database, but this means that the same needs to be processed every time it is presented to users around the world.

Instead, it is smarter to defer this processing to the client side, that is, the browser. The browser always knows the current time zone of its user and will therefore be able to manipulate the date and time information correctly. This approach also reduces any unnecessary overhead from our application servers. In this recipe, we will understand how to achieve this. We will use Moment.js for this purpose.

In this recipe, it is assumed that...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Flask Framework Cookbook. - Second Edition
Published in: Jul 2019Publisher: ISBN-13: 9781789951295
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Shalabh Aggarwal

Shalabh Aggarwal has more than 13 years' experience in developing and managing enterprise systems, as well as web and mobile applications for small-to large-scale industries. He started his career working on Python, and although he now works on multiple technologies, he remains a Python developer at heart. He is passionate about open source technologies and writes highly readable and quality code. He is a seasoned engineering leader who loves building engineering teams and products from scratch across multiple domains while leveraging different technologies. He is also active in voluntary training for engineering students on non-conventional and open source topics. When not working with full-time assignments, he consults for start-ups on leveraging different technologies. When not writing code, he writes technical and non-technical literature, which is published across multiple blogs.
Read more about Shalabh Aggarwal