- Flask Framework Cookbook(Second Edition)
- Shalabh Aggarwal
- 183字
- 2021-06-24 13:58:03
How to do it...
One of the most redundant pieces of code in HTML is that which defines input fields in forms. This is because most fields have similar code with style modifications, for example.
The following snippet is a macro that creates input fields when called. Best practice is to create the macro in a separate file for better reusability, for example, _helpers.html:
{% macro render_field(name, class='', value='', type='text') -%} <input type="{{ type }}" name="{{ name }}" class="{{ class }}" value="{{ value }}"/> {%- endmacro %}
The minus sign ( -) before and after % will strip the whitespace before and after these blocks, making the HTML code cleaner to read.
Now the macro should be imported in the file to be used, as follows:
{% from '_helpers.html' import render_field %}
It can now be called using the following code:
<fieldset> {{ render_field('username', 'icon-user') }} {{ render_field('password', 'icon-key', type='password') }} </fieldset>
It is always good practice to define macros in a different file to keep the code clean and increase code readability.
If you need to write a private macro that cannot be accessed from outside its current file, name the macro with an underscore preceding the name.