In
Django - Lesson 035. Different templates for rendering different types of content in search results
it was shown how to render different templates depending on what type of content drawn in the search results on the site. In this case, the key point was that it was not necessary to make the verification conditions for the selection of the template. The information about the balbalon was stored in the variable TEMPLATE_PREVIEW, through which the template was inserted into the include tag in the Django template.

{% include object.TEMPLATE_PREVIEW %}

In this method there is one big drawback. The fact is that the include tag with each of its calls is looking for a template. With a large load on the site - this can significantly increase the duration of the response from the server. To solve this problem, you need to somehow cache the pattern. Since different types of content use different templates, to do this using inclusion_tag is quite problematic.

This problem was solved by caching the template at the class level as a class variable.

This mechanism can be implemented using a mixin.

class EInterfaceMixin:
TEMPLATE_FULL = 'full.html' # путь к шаблону
template_full = None # pattern caching variable
# we will cache with the help of the class method, in which we pass the object for rendering, as well as the context of the request
# request context is required to provide rendering functionality that is dependent on the current user
@classmethod
def __render_template_full(cls, obj, request_context):
if not cls.template_full:
cls.template_full = loader.get_template(cls.TEMPLATE_FULL)
return cls.template_full.render({'object': obj, 'user': request_context['user']})
# method to render using context
def render_template_full(self, request_context):
return self.__render_template_full(self, request_context)

Next you need to register the built-in tag. This is necessary so that when rendering in a template, pick up the context of the request. In my case, part of the templates can not be correctly displayed without information about the current user who is on the site.

Conclusion

This mixin can be added to all models that will use this rendering engine.

The first time the class method is called, the template will be cached. In subsequent render calls, the already cached template will be used. Thus, there will be no useless CPU time spent on searching for a template with each call of the
include
tag