0

Suppose I want to override a Jinja macro with a function defined in routes.py that returns None. I attempted to use a Context Processor (@app.context_processor) but it didn’t override the macro. (It outputs the assignment made in macros.html.)

routes.py

@app.context_processor
def thing():
        def my_macro():
                return None
    return dict(my_macro=my_macro)

macros.html

{% macro my_macro() %}Arbitrary_text{% endmacro %}

The reason I am doing this is so I can add some conditional datetime logic using python (instead of writing it in Jinja).

Context Processor documentation is here: https://flask.palletsprojects.com/en/2.2.x/templating/#context-processors

silian-rail
  • 135
  • 10

1 Answers1

0

You still have to remove import calls made to my_macro in your templates (and remove {# or comment out #} the definition in macros.html) but the following will work:

@app.add_template_global
def my_macro():
    return None

For more: https://flask.palletsprojects.com/en/2.2.x/api/#flask.Flask.add_template_global,

Call a python function from jinja2

silian-rail
  • 135
  • 10