[Django]-Django – Simple custom template tag example

98πŸ‘

βœ…

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>

17πŸ‘

Inline HTML in tag

If the HTML is small, this method is more convenient than creating a separate file.

This example factors out links to user profiles. The file templatetags/somemodule.py contains:

from django import template
from django.template import Template

register = template.Library()

@register.simple_tag(takes_context=True)
def user_link(context):
    return Template('<a href="{% url \'user_detail\' ' +
            'user.id %}">{{ user.username }}</a>').render(context)

Template#render already returns a safe string which is not XSS escaped. E.g. if we had done just:

return '<br>'

it would be escaped. You might also want to play with mark_safe.

You can make that tag available on all views with:

TEMPLATES = [
    {
        'OPTIONS': {
            'builtins': [
                'myprojectname.templatetags.somemodule',

in settings.py.

See also:

Leave a comment