Categories
Python Answers

How to create a simple custom template tag with Python Django?

Spread the love

To create a simple custom template tag with Python Django, we can create a function.

For instance, we write

from django import template

register = template.Library()

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

in templatetags/video.tags.py by creating the get_rate function that returns a value and register it with the @register.simple_tag decorator.

Then in a template, we load and use the tag with

{% 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>

We load it with

{% load video_tags %}

And then we use the get_rate tag with

{% get_rate crit rates %}

rates is the argument for the tag function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *