Skip to content

Instantly share code, notes, and snippets.

@kofic
Last active February 25, 2019 16:26
Show Gist options
  • Select an option

  • Save kofic/f37c6ab17566914139b2744ada8523fe to your computer and use it in GitHub Desktop.

Select an option

Save kofic/f37c6ab17566914139b2744ada8523fe to your computer and use it in GitHub Desktop.

Let's say you have a Django app called sections - your templatetag will be in the following folder:


 sections/
      __init__.py
      models.py
      ...
      templatetags/
          __init__.py
          sections_tags.py
          

Your templatetags will be defined in sections_tags.py

There are 3 kinds of template tags:

  • simple_tag: Processes the data and returns a string
  • inclusion_tag: Processes the data and returns a rendered template
  • assignment_tag: Processes the data and sets a variable in the context

We will focus on simple_tag for this example.

Let's say we want to create a simple_tag called get_section_content which we will get data from the SectionContent model given a Section name and SectionContent name. This is what our models and templatetags will look like:

# models.py

from django.db import models


class Section(models.Model):
    name = models.CharField(max_length=200, unique=True)

def __str__(self):
    return "Section: %s" % self.name


class SectionContent(models.Model):
    name = models.CharField(max_length=200)
    section = models.ForeignKey('Section', related_name="section_sectioncontent", on_delete=models.CASCADE)
    html = models.TextField(null=True, blank=True)
    image = models.FileField(null=True, blank=True)

    class Meta:
        unique_together = ('name', 'section',)
        
def __str__(self):
    return "Section Content: %s -> %s" % (self.section.name, self.name)

Now our templatetag file will look like

# sections_tags.py
from django.utils.safestring import mark_safe

from django import template
register = template.Library()

from sections.models import Section, SectionContent

@register.simple_tag
def get_section_content(section_name, section_content_name, content_type):
    try:
       section_content = SectionContent.objects.get(
            section = Section.objects.get(name=section_name),
            name = section_content_name
        )
          
        if content_type == "html":
            return mark_safe(section_content.html)
        elif content_type == "image":
            return section_content.image.url
    except SectionContent.DoesNotExist:
        pass
    except Section.DoesNotExist:
        pass

Finally - in your template you will use your templatetags to get the data like this:


{% load sections_tags %}

<div class="left-block">
    {% get_section_content "contact_us" "contact_us_left_block" "html" %}
</div>
<div class="right-block">
    <img src="{% get_section_content "contact_us" "contact_us_right_block" "image" %}">
</div>

This code means:

# Load the sections_tags.py file
{% load sections_tags %}
# Call the get_section_content function with the arguments "contact_us", "contact_us_left_block" and "html"
# The section name is "contact_us"
# The section_content_name is "contact_us_left_block"
# The content type is "html"
{% get_section_content "contact_us" "contact_us_left_block" "html" %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment