django-sekizai icon indicating copy to clipboard operation
django-sekizai copied to clipboard

Is it possible to detect an empty block?

Open iarp opened this issue 2 years ago • 0 comments

I have a render_block that displays a nav-item on specific portions of my website and I would like a "default" type menu displayed in its place when no nav-item exists.

I'd love to be able to do something like

{% render_block "nav-item" %}
{% emptyblock "nav-item" %}
    my default menu here which only displays when there are no rendered nav-item blocks.
{% endemptyblock %}

I was able to get a working sample going in development by copying addtoblock and tweaking things. I'm not sure if its an idea worthy of actually adding to this project.

class EmptyBlockParser(Parser):
    def parse_blocks(self):
        name = self.kwargs['name'].var.token
        self.blocks['nodelist'] = self.parser.parse(
            ('endemptyblock', 'endemptyblock %s' % name)
        )
        self.parser.delete_first_token()

class EmptyBlock(SekizaiTag):
    name = 'emptyblock'

    options = Options(
        Argument('name'),
        Flag('strip', default=False, true_values=['strip']),
        'preprocessor',
        Argument('preprocessor', required=False, default=None, resolve=False),
        parser_class=EmptyBlockParser,
    )

    def render_tag(self, context, name, strip, preprocessor, nodelist):
        rendered_contents = nodelist.render(context)
        if strip:
            rendered_contents = rendered_contents.strip()
        if preprocessor:
            func = import_processor(preprocessor)
            rendered_contents = func(context, rendered_contents, name)
        varname = get_varname()
        existing = context[varname][name]
        if not existing:
            return rendered_contents
        return ""


register.tag('emptyblock', EmptyBlock)

iarp avatar Jul 29 '23 13:07 iarp