官术网_书友最值得收藏!

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 }}" class="{{ class }}"
        value="{{ value }}"/>
{%- endmacro %}

Note

The minus sign (-) before/after % will strip the whitespaces after and before these blocks and make the HTML code cleaner to read.

Now, this macro should be imported in the file to be used:

{% from '_helpers.jinja' import render_field %}

Then, it can simply be called using the following:

<fieldset>
    {{ render_field('username', 'icon-user') }}
    {{ render_field('password', 'icon-key', type='password') }}
</fieldset>

It is always a good practice to define macros in a different file so as to keep the code clean and increase code readability. If a private macro that cannot be accessed out of the current file is needed, then name the macro with an underscore preceding the name.

主站蜘蛛池模板: 施甸县| 雷山县| 会昌县| 夏邑县| 宣恩县| 巴彦淖尔市| 南安市| 安岳县| 布尔津县| 肃北| 临沧市| 克山县| 泰宁县| 青神县| 卢氏县| 禹州市| 务川| 龙游县| 防城港市| 宣化县| 晋江市| 黄平县| 黔西县| 拉萨市| 祁连县| 梁河县| 江川县| 秭归县| 安阳市| 兴仁县| 松滋市| 信宜市| 沙坪坝区| 天柱县| 饶平县| 潜山县| 尼玛县| 德保县| 天峨县| 万载县| 集安市|