Django base.html block overwriting

65 Views Asked by At

I want to define, and append to blocks defined in the base.html template.

Say I have the following template

<!DOCTYPE html>
<html>
    <head>
        <title>My Project</title>
        {% block append_to_me %}{% endblock %}
    </head>

    <body>
    {% block content %}{% endblock content %}
    </body>
</html>

I would then use the following template for my views, my views render some wagtail components, and those components might want to use the append_to_me block.

This goes not only for the wagtail blocks, but also for plain django template tags

{% extends "base.html" %}

{% block content %}
    <h2>Content for My App</h2>
    <p>Stuff etc etc.</p>
    {# I want it to not matter where I use this. #}
    {% my_custom_tag %}
{% endblock content %}

Where {% my_custom_tag %} would do something like this:

@register.simple_tag(takes_context=True)
def my_custom_tag(context):
    objects = Preload.objects.all()
    for object in objects:
        append_to_header_block(object.html)

Wagtail block example:

class MyBlock(blocks.StructBlock):
    title = blocks.CharBlock()
    content = blocks.RichTextBlock()

    class Meta:
        template = 'myapp/myblock.html'

myapp/myblock.html

{% add_to_header IMG "img/my-img.jpeg" %}
...

I also want to be able to keep the content of previous calls to the add_to_header function, as to not overwrite the previous content.

I just cannot figure out how I would implement this, because there are a few issues:

  • Order of evaluation, I am pretty sure the content of base.html gets rendered before any of the other templates.
    • Maybe this can be fixed by somehow overwriting the append_to_me block from anywhere; and calling block.super every time? Somehow would be my question.
  • Wagtail blocks might not even know they are not used in base.html due to their versatility.

Any ideas as to how I would implement this? I am not even sure if this is possible, but I would love to hear your thoughts on this.

0

There are 0 best solutions below