我在 mytag.py 文件中有一个 mytag 的标签定义。当我使用带有 settings.py 和 INSTALLED_APPS 的 Django 项目时,这很好用——我将“myapp”附加到列表中,并将 mytag.py 放在 myapp/templatetags 中。
现在我正在使用 django.conf.settings.configure 并且我没有带有 templatetags 子目录的模块——如何加载 mytag.py?
更新:
我现在尝试使用带有 templatetags 目录的模块,但我无法让它工作。这是我的设置:
文件:
- 我的应用
__init.py__
- 模板标签
__init__.py
- mytag.py
- 程序
- 测试.py
- 测试.html
这是相关代码:
# test.py
from django.template import Template, Context
from django.conf import settings
from mostlystatic.processors.mostlystaticprocessor import MostlystaticProcessor
from mostlystatic.stuff import DebugLogger
import sys
sys.path.append("~/")
settings.configure(
DEBUG=True,
TEMPLATE_DEBUG = True,
INSTALLED_APPS = ("myapp",)
)
t = Template(open("test.html").read())
c = Context({})
content = t.render(c)
print content
# test.html
{% load mytag %}
# mytag.py (doesn't load)
from classytags.arguments import Argument
from classytags.core import Tag, Options
from django import template
register = template.Library()
class MyTag(Tag):
name="mytag"
def render_tag(self, context:
return "test"
register.tag(MyTag)
当我运行 test.py 时,我收到以下消息:
Traceback (most recent call last):
File "test.py", line 16, in <module>
t = Template(open("test.html").read())
File "/Library/Python/2.7/site-packages/django/template/base.py", line 125, in __init__
self.nodelist = compile_string(template_string, origin)
File "/Library/Python/2.7/site-packages/django/template/base.py", line 153, in compile_string
return parser.parse()
File "/Library/Python/2.7/site-packages/django/template/base.py", line 270, in parse
compiled_result = compile_func(self, token)
File "/Library/Python/2.7/site-packages/django/template/defaulttags.py", line 1033, in load
(taglib, e))
django.template.base.TemplateSyntaxError: 'mytag' is not a valid tag library: Template library mytag not found, tried django.templatetags.mytag