Search code examples
djangodjango-templatesdjango-filterdjango-tagging

check that tag is used in template only once


I write a custom tag for using in django templates: {% my_custom_tag %}.

Using django channels it extends some page functionality. But I a worried that users may by accident insert this tag twice to a template, and that can create some issues because channels will deliver the same info twice etc.

Is there any relatively simple way to check that the tag is used in a template only once and raise an error otherwise?


Solution

  • You could maniplate the context, and set a certain key (preferably one that is not used by other applications) to True, and raise an exception otherwise. For example:

    @register.simple_tag(takes_context=True)
    def my_custom_tag(context):
        if '__some_weird_name__for_my_custom_tag' in context:
            raise Exception('my_custom_tag is already used')
        context['__some_weird_name__for_my_custom_tag'] = True
        # ...
        # do other logic
        pass

    Of course the condition is that you do not pass content with this name to the context initially.

    Furthermore if you would perform multiple render(..)s in a view, these will usually have a separate context, but this is probably desired.

    Note that the error is raised at runtime. We thus do not proactively detect templates where this happens, but we will get an error if it happens.