Django – Simple custom template tag example

Here is my solution (based on a custom tag):

Firstly create the file structure. Go into the app directory where the tag is needed, and add these files:

templatetags
templatetags/__init__.py
templatetags/video_tags.py

The templatetags/video_tags.py file:

from django import template

register = template.Library()

@register.simple_tag
def get_rate(crit, rates):
    return rates.get(crit=crit).rate

The template part, with our tag call:

{% load video_tags %}

<div id="rating">
  <ul>
{% for crit in videofile.topic.crits.all %}
    <li>
      <div class="rateit"
        data-rateit-value="{% get_rate crit rates %}"
        data-rateit-ispreset="true"
        crit-id="{{ crit.id }}"></div>
      {{ crit }}
    </li>
{% endfor %}
  </ul>
</div>

Leave a Comment