2012-02-23 52 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