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?
did you try this
at the top instead of pygmentize?
The app that contains the custom tags must be in
INSTALLED_APPS
. So Are you sure that your directory is inINSTALLED_APPS
?From the documentation:
In
gameprofile.html
please change the tag{% endblock content %}
to{% endblock %}
then it works otherwise django will not load the endblock and give error.I had the same problem, here's how I solved it. Following the first section of this very excellent Django tutorial, I did the following:
python manage.py startapp new_app
settings.py
file, adding the following to the list ofINSTALLED_APPS
:'new_app',
new_app
package namednew_app_tags
.{% extends 'base_template_name.html' %}
:{% load new_app_tags %}
new_app_tags
module file, create a custom template tag (see below).{% multiply_by_two | "5.0" %}
Example from step 5 above:
You need to change:
to
The error is in this line:
(% load pygmentize %}
, an invalid tag. Change it to{% load pygmentize %}