[Answered ]-Django Do Once Custom Template Tag


I’m not exactly sure what you need to accomplish or if your approach is indeed the best approach, but I’d suggest your look into the forloop.first variable before you go too far down this road. Your approach seems awkward at best at a glance, but I could be wrong since I don’t know the specifics of the situation

django for template tag

Most likely you should be able to make this work to your needs, however if it falls short I’d suggest that the source for the for template tag (and it’s forloop variable) would likely be very illustrative on how you might implement what you’re looking to do.



What I ended up doing is saving a variable within the context and checking for that in the Node’s render method:

class CustomNode(template.Node):
    def render(self, context: dict) -> str:
        context['already_rendered'] = context.get('already_rendered', set())

        if self.__class__ in context['already_rendered']:
            return ''



Leave a comment