Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to detect an empty block? #162

Open
iarp opened this issue Jul 29, 2023 · 0 comments
Open

Is it possible to detect an empty block? #162

iarp opened this issue Jul 29, 2023 · 0 comments

Comments

@iarp
Copy link

iarp commented Jul 29, 2023

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant