Using Jinja Macros

From PeformIQ Upgrade
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

Other Links


Tooltip

From stackoverflow.com/questions/4247599/jinja-macros-accessing-different-blocks

for every tooltip on a page, give every tooltip a class attribute and make the jQuery functionality work on all elements with that class. That way, every page can have the same generic bit of jQuery and work regardless of what tooltips appear on that specific page.

Something more like:

<div id="mytool" class="tooltip">
  This is my tooltip
</div>

plus a more generic jQuery call:

<script>
  // This will add the onclick handler to any element
  // with a class of "tooltip"
  jQuery(".tooltip").click(function(){});
</script>

This jQuery code can be included once, at the bottom of your "base" template, so that it's available on every page and you don't have to figure out how to write to two separate blocks from a Jinja macro.