Search code examples
pythonflaskjinja2

How to edit some extends block in jinja2?


I have a base template named main.html:

<ul>
  <li>index</li>
  <li>about</li>
  <li>contacts</li>
</ul>

And I have a template index.html, which has:

{% extends "main.html" %}

How I can add class atributes into <li> tags depending on named heir?

For example, if index.html extends main.html, then I add class="active" to first <li>, if about.html extends main.html, then I add class="active" to second <li> .... and so on.

How I can do it?


Solution

  • there are kinda two solution to this:

    the first way is defining a macro and calling it from child pages(not the inherited main page) which contain information to make which <li> active.

    like :

    {% macro menu(active) %}
    
    <ul>
      {% if active == 'index' %}<li class="active">{% else %}<li>{%endif%}index</li>
      {% if active == 'about' %}<li class="active">{% else %}<li>{%endif%}about</li>
      {% if active == 'contacts' %}<li class="active">{% else %}<li>{%endif%}contacts</li>
    </ul>
    
    {% endmacro %}
    

    and use it as :

    {% from 'macro.html' import menu %}
    
    {{ macro('index') }} #in index.html
    {{ macro('about') }} #in about.html
    {{ macro('contacts') }} #in contacts.html
    

    another ways is using the magical g variable. in your view functions define which item should be the active one and put in the g variable. like:

    from flask import g
    
    app.route('/about')
    def about():
      ...
      g.active_menu_item = 'about'
    
      ...
    
      return render_template('about.html')
    

    and your about.html(index and contacts too) inherits from main.html', so the codes that render menu ofmain.htmlshould considerg.active_menu_item` into account. like:

    main.html :

    <ul>
      {% if g.active_menu_item == 'index' %}<li class="active">{% else %}<li>{%endif%}index</li>
      {% if g.active_menu_item == 'about' %}<li class="active">{% else %}<li>{%endif%}about</li>
      {% if g.active_menu_item == 'contacts' %}<li class="active">{% else %}<li>{%endif%}contacts</li>
    </ul>