This snippet adds simple partial support to your templates. You can pass data to the partial, and use it as you would in a regular template. It is different from Django's {% include %}
, because it allows you to pass a custom variable (context), instead of reusing the same context for the included template. This decouples the templates from each other and allows for their greater reuse.
The attached code needs to go into templatetags
folder underneath your project. The usage is pretty simple - {% load ... %}
the tag library, and use {% partial_template template-name data %}
in your template. This will result in template passed as template-name to be loaded from partials folder. The .html extension will be appended to the file name. The file has to be in one of template paths accessible to the loader) and rendered with data as its context. The data is available in the template as an item
context variable.
You can find more information in the relevant Django documentation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | from django.template import Library, Node, Variable, loader from django.template.context import Context register = Library() class PartialTemplateNode(Node): def __init__(self, template_name, context_item): self.template_name = template_name self.context_item = Variable(context_item) def render(self, context): template = loader.get_template('partials/%s.html' % (self.template_name,)) item = self.context_item.resolve(context) template_context = Context({ 'item': item }) return template.render(template_context) @register.tag def partial_template(parser, token): tag, template_name, context_item = token.split_contents() return PartialTemplateNode(template_name, context_item) |
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Great idea. Thanks
#
I like it, but would rather have "partials/" come from a setting, so that I could use "_" instead. (Keeping partials in the same directory with the templates they're used in is one less place to look.)
#
Please login first before commenting.