[ACCEPTED]-Django - Simple custom template tag example-django-templates

Accepted answer
Score: 97

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

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


The templatetags/video_tags.py file:

from django import template

register = template.Library()

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

The template part, with 1 our tag call:

{% load video_tags %}

<div id="rating">
{% for crit in videofile.topic.crits.all %}
      <div class="rateit"
        data-rateit-value="{% get_rate crit rates %}"
        crit-id="{{ crit.id }}"></div>
      {{ crit }}
{% endfor %}
Score: 17

Inline HTML in tag

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

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

from django import template
from django.template import Template

register = template.Library()

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 5 which is not XSS escaped. E.g. if we had 4 done just:

return '<br>'

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

You can make that 2 tag available on all views with:

        'OPTIONS': {
            'builtins': [

in settings.py.

See 1 also:

More Related questions