[Answer]-Using jinja2 macro from filter using jingo

1👍

After a bit of investigation I came out with a solution. Macros are defined in templates, so first of all I needed to load it. Reading the source code I found out how to get the macro function from a template instance, so here’s the correct way to do so:

@register.filter()
def as_link(obj_or_list):
    from jingo import env

    template = env.get_template('macros.html')
    render_link = template.module.render_link

    if hasattr(obj_or_list, '__iter__'):
        return ''.join((render_link(obj) for obj in obj_or_list))
    return render_link(obj_or_list)

0👍

I do not know if this works, but maybe the macro is registered as a global function. Macros and Global Python functions can be called in the same way from a template.

If your macro was registered, you can :

env.globals['render_link'](obj)

If this does now work, you can always include the macro code as Python code in your filter. In your filter you have all the Python power.

Leave a comment