【问题标题】:Django custom template tags not loadingDjango自定义模板标签未加载
【发布时间】:2016-02-25 20:14:33
【问题描述】:

我在我的 Django 1.8 项目中使用自定义模板标签时遇到问题。这就是发生的事情:

TemplateSyntaxError at /
Invalid block tag: 'custom_foo'
Request Method: GET
Request URL:    <...>
Django Version: 1.8.3
Exception Type: TemplateSyntaxError
Exception Value:    
Invalid block tag: 'custom_foo'

我的文件夹如下所示:

my_app
|---templatetags
    |---__init__.py
        myapp_extras.py

还有myapp_extras.py

from django import template
register = template.Library()

@register.filter
def custom_foo():
    return 'bar'

我正在使用 PyCharm5 进行开发。 一定是少了什么。

我的 base.html 模板顶部有 {% load myapp_extras %}

【问题讨论】:

    标签: django pycharm templatetags


    【解决方案1】:

    您已将custom_foo()注册为过滤器,请尝试根据:https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/将其注册为标签,例如:

    from django import template
    register = template.Library()
    
    class BarNode(template.Node):
      def render(self, context):
        return 'bar'
    
    @register.tag
    def custom_foo(parser, token):
      return BarNode()
    

    【讨论】:

    • 这有帮助。但是render() takes exactly 1 argument (2 given),所以def render(self, somevar)。现在我必须弄清楚为什么(或重写)django_hijack 以便标签工作。这是 1.8 的最新变化吗?
    • 我明白了。 django-hijack 在他们的文档中有一个错误。我得到的错误是对过滤器使用标签实现的结果,这是行不通的。谢谢@Adrian!
    猜你喜欢
    • 2017-07-29
    • 2019-12-30
    • 2010-11-15
    • 2011-07-10
    • 2016-05-05
    • 2020-10-02
    • 2021-07-13
    • 2015-01-20
    相关资源
    最近更新 更多