2012-02-23 54 views
1

我在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 
+0

你想从一个不存在的应用中包含你的标签吗? – arie 2012-02-23 11:53:47

+1

“我曾经拥有<遵循文档的东西>,现在我想要做<完全打破项目应该配置的方式的东西>,我该怎么做?” – 2012-02-23 11:58:37

+0

@arie我还有标签文件,我只用它来测试它。 – fgm2r 2012-02-23 11:59:04

回答

3

最简单的方法是创建一个带有templatetags子目录的模块,并在配置设置时将该模块包含在INSTALLED_APPS中。

其他任何方法都会涉及与Django内部的摔跤。

如果您的脚本无法正常工作,请尝试将它剥下来,如下所示,然后重新构建。

from django.conf import settings 
settings.configure(INSTALLED_APPS=('my_app',)) 

from django.template import Template 
# my_tags does not exist, but the error shows that it is 
# searching my_app's template tag directory 
Template.render("{% load my_tags %}") 
TemplateSyntaxError: 'my_tags' is not a valid tag library: Template library my_tags not found, tried django.templatetags.my_tags, my_app.templatetags.my_tags 
+0

谢谢,我会尝试。这并不理想,但我认为它会做。 – fgm2r 2012-02-23 12:00:06

+0

我试过了,但它仍然无法正常工作。你有什么想法,为什么? – fgm2r 2012-02-23 12:31:25

+0

我看不到问题,但我可以找到一个简单的示例来工作,我已将其添加到我的答案中。从那开始,然后建立起来。 – Alasdair 2012-02-23 14:44:14