我在mytag.py文件中有一个mytag的标签定义。当我使用带有settings.py和INSTALLED_APPS的Django项目时,此工作正常 - 我将'myapp'追加到列表中,并将mytag.py放在myapp/templatetags中。如何从文件加载自定义Django标签?
现在我正在使用django.conf.settings.configure,并且我没有带templatetags子目录的模块 - 我如何加载mytag.py?
更新:
我现在试图用一个模块创建一个templatetags目录,但我不能得到它的工作。这里是我的设置:
文件:
- MYAPP
__init.py__
- templatetags
__init__.py
- mytag.py
- 程序
- test.py
- 的test.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
你想从一个不存在的应用中包含你的标签吗? – arie 2012-02-23 11:53:47
“我曾经拥有<遵循文档的东西>,现在我想要做<完全打破项目应该配置的方式的东西>,我该怎么做?” – 2012-02-23 11:58:37
@arie我还有标签文件,我只用它来测试它。 – fgm2r 2012-02-23 11:59:04