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 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 like we do to functions in Python and then use them to process the HTML block. Macros can be called any number of times, and the output will vary as per the logic inside them.

Getting ready

Working with macros in Jinja2 is a very common topic and has a lot of use cases. Here, we will just see how a macro can be created and then used after importing.

How to do it…

One of the most redundant pieces of code in HTML is defining input fields in forms. Most of the fields have similar code with some modifications of style and so on. The following is a macro that creates input fields when called. The best practice is to create the macro in a separate file for better reuseability, for example, _helpers.html:

{% macro render_field(name, class='', value='', type='text') -%}
    <input type="{{ type }}" name="{{ name...