I am using Flask/Jinja2 and Bootstrap 3.
I\'d like to add class=\"active\" to the current navigation element.
Those elements are stored in
Use Jinja2 macro in correct way. It's really an useful feature. In this case you do not have a proper understanding how it works. This post will explain it well hopefully. This is the macro for nav menu. Remember to put this macro somewhere above nav menu code. Otherwise Jinja won't find it when needed.
{% macro nav_link(endpoint, name) %}
{% if request.endpoint.endswith(endpoint) %}
- {{name}}
{% else %}
- {{name}}
{% endif %}
{% endmacro %}
You have to define this code block separately in your template file. Do not put it in a loop or anywhere else. When you call the macro anywhere in your template this code block will execute and give you the desired output. See how to use this macro. nav-link() is like a regular function. Call it in your navbar code block. Remember You have to define these routes in server first. OR you can add these macros in a separate html files (let's say macros.html) and import any macro in it, anywhere you want.
If you are using macros.html like I mentioned above, you can use following code to import your macro.
{% from "macros.html" import nav_link with context %}
This is a good tutorial for jinja2 templating.