Custom tag not loaded in template

123 picture 123 · Jan 28, 2016 · Viewed 118.1k times · Source

I've created a custom tag that I want to use, but Django can't seem to find it. My templatetags directory is set up like this:

pygmentize.py

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from django import template
from pygments.formatters.other import NullFormatter

register = template.Library()

@register.tag(name='code')
def do_code(parser,token):
    code = token.split_contents()[-1]
    nodelist = parser.parse(('endcode',))
    parser.delete_first_token()
    return CodeNode(code,nodelist)

class CodeNode(template.Node):
    def __init__(self,lang,code):
        self.lang = lang
        self.nodelist = code

    def render(self,context):
        code = self.nodelist.render(context)
        lexer = get_lexer_by_name('python')
        return highlight(code,lexer,NullFormatter())

I am trying to use this tag to render code in gameprofile.html.

gameprofile.html

(% load pygmentize %}
{% block content %}
    <title>{% block title %} | {{ game.title }}{% endblock %}</title>
    <div id="gamecodecontainer">
        {% code %}
            {{game.code}}
        {% endcode %}
    </div>
{% endblock content %}

When I navigate to gameprofile.html, I get an error:

Invalid block tag on line 23: 'code', expected 'endblock'. Did you forget to register or load this tag?

Answer

Erick M picture Erick M · Jan 24, 2017

The error is in this line: (% load pygmentize %}, an invalid tag. Change it to {% load pygmentize %}