Using Jinja Macros

From PeformIQ Upgrade
Revision as of 14:42, 10 January 2015 by PeterHarding (talk | contribs) (Created page with "=Macros= <i>from https://realpython.com/blog/python/primer-on-jinja-templating/</i> In Jinja, we can use macros to abstract commonly used code snippets that are used over...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Macros

from https://realpython.com/blog/python/primer-on-jinja-templating/


In Jinja, we can use macros to abstract commonly used code snippets that are used over and over to not repeat ourselves. For example, it’s common to highlight the link of the current page on the navigation bar (active link). Otherwise, we’d have to use if/elif/else statements to determine the active link. Using macros, we can abstract out such code into a separate file.

Add a macros.html file to the “templates” directory:

{% macro nav_link(endpoint, name) %}
{% if request.endpoint.endswith(endpoint) %}
  <li class="active"><a href="{{ url_for(endpoint) }}">{{name}}</a></li>
{% else %}
  <li><a href="{{ url_for(endpoint) }}">{{name}}</a></li>
{% endif %}
{% endmacro %}

Here, we’re using Flask’s request object, which is part of Jinja by default, to check the requested endpoint, then assigning the active class to that endpoint.

Update the unordered list with the nav navbar-nav class in the base template:

<ul class="nav navbar-nav">
  {{ nav_link('home', 'Home') }}
  {{ nav_link('about', 'About') }}
  {{ nav_link('contact', 'Contact Us') }}
</ul>

Also, make sure to add the import at the top of the template: {% from "macros.html" import nav_link with context %}.

Notice how we’re calling the nav-link macro and passing it two arguments, the endpoint (which comes from our controller) and the text we want displayed