0

我在我的 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 %}位于顶部。

4

1 回答 1

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()
于 2015-11-23T16:47:34.973 回答