Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redefine macro in jinja2

Tags:

python

jinja2

I'm using jinja2 through sphinx. In my base template (layout.html I have some some macro

{%- macro post_meta(metadata) -%}
    <div class="postmeta">
        {{ author(metadata.author) }}
    </div>
{%- endmacro -%}

I'm extending this template in theme2 with {%- extends "theme1/layout.html" -%}

How can I redefine post_meta in theme2? Simple putting new definition of post_meta in theme2 doesn't work.

By the way how can I use python buildin function like:

{{ type(metadata) }}
like image 654
Robert Zaremba Avatar asked Dec 11 '12 12:12

Robert Zaremba


1 Answers

Q1: You have to create a block to override the block with the macro in your base template. This is the code for the child. With use_child = False : the macro in the base template will be used

{% block pm_mac %}
    {% if use_child %}
        {%- macro post_meta(metadata) -%}
               .....
        {%- endmacro -%}
    {% else %}        
        {{ super() }}
    {% endif %} 
{% endblock %} 

Q2: You have to register a global Python function to use type :

def py_to_upper(a):
    return a.upper()

env.globals['to_upper'] = py_to_upper # register the global python function


and in the Jinja template :

{{ to_upper("lowercase") }}   
like image 89
voscausa Avatar answered Oct 22 '22 04:10

voscausa