django - 自定义标签未加载到模板中

标签 django django-templates pygments

我已经创建了一个我想使用的自定义标签,但 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 时,出现错误:

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

最佳答案

对于 Django 2.2 到 3,在使用 static 关键字之前,您必须先在 html 模板中加载 staticfiles

{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

对于其他版本使用static

{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">

此外,您还必须检查您是否在 setting.py 中定义了 STATIC_URL

最后,确保静态文件存在于定义的文件夹中

关于django - 自定义标签未加载到模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35054230/

相关文章:

java - Jython - 在 Java 项目中使用 Pygments

jekyll - 在 Jekyll 中显示文件名并突出显示 Pygments 代码

python - 通过模型的属性(而不是字段)对 Django QuerySet 进行排序

python - Django 模板 : key, 值在 for 循环中不可能

python - django 模板中 "none"的等价物是什么?

django - 部署 Django 项目的不同方法及其优缺点?

python - 更改pythonpath的优先级

python - Django admin 在同一行显示多个字段

django post_save 信号和 ManyToManyField(和 Django Admin)

python - 在django中,我可以在if标签中使用 'as'吗,比如: {% if excessively_verbose. chain_of_long.nested_references as foo%}