【发布时间】:2016-05-05 09:36:21
【问题描述】:
我创建了一个我想使用的自定义标签,但 Django 似乎找不到它。我的templatetags 目录是这样设置的:
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())
我正在尝试使用此标记来呈现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 %}
当我导航到 gameprofile.html 时,我收到一个错误:
第 23 行的块标记无效:'code',预期为 'endblock'。您是否忘记注册或加载此标签?
【问题讨论】:
-
{% do_code %}{% endcode %}有效吗? (是不是忽略了名字) -
我试过了,
do_code也不行。 -
嗯,对我来说,唯一看起来不合适的是你在一个块内有一个块......不确定这是否会影响事情(标题) . (我可能是错的,我不认为我使用任何嵌套块)
-
标题已经有一段时间了,没有问题。虽然
{% code %}部分的块内也有一个块...... -
是的,我再次明确地指的是
block标签,但我想有时你只希望一个块显示另一个块是否存在......我真的看不出来您的代码有任何问题,当然我认为您已经重新启动了runserver命令
标签: django django-templates pygments