我想从模板访问一些帮助程序函数,但在访问这些函数时遇到问题。将 Jinja2 与 Coffin 一起使用(这很棒,除了我似乎无法访问我的全局函数(。
我在 jinja.py 中注册我的对象
from coffin.template import Library
register = Library()
@register.object(name='tester')
def tester():
return 'TESTING YAA!!'
print (register.jinja2_globals)
我的模板测试器.html看起来像这样:
{{ tester() }}
但事实就是如此:
>>> from apps import jinja
{'tester': <function tester at 0x3133938>}
>>> jinja.tester()
'TESTING YAA!!'
导入工作正常,函数注册正确,但无法使用render_to_response或render_to_string访问:
>>> from coffin.template.loader import render_to_string as rts
>>> rts('tester.html')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/pydev/drew/iame/lib/python2.6/site-packages/Coffin-0.3.7.dev-py2.6.egg/coffin/template/loader.py", line 55, in render_to_string
return template.render(context_instance)
File "/pydev/drew/iame/lib/python2.6/site-packages/Coffin-0.3.7.dev-py2.6.egg/coffin/template/__init__.py", line 56, in render
return super(Template, self).render(**context)
File "/pydev/drew/iame/lib/python2.6/site-packages/jinja2/environment.py", line 894, in render
return self.environment.handle_exception(exc_info, True)
File "/pydev/drew/iame/iame_cms/apps/templates/tester.html", line 1, in top-level template code
{{ tester() }}
UndefinedError: 'tester' is undefined
但在我的模板中无法访问:(
要加载你的库,它必须位于标准位置,即 Django 期望这样的库的位置:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#code-layout
即,类似于my_app/templatetags/customlib.py
.