Google App Engine中Django的customer template tags的使用

在GAE中使用Django的时候,自定义标签是不可避免的。

今天遇到这个问题的时候,按照Django的官方做法来做:

http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

发现总是报错,告诉我<%load mytemplate%>找不到:

mytemplate is not a valid tag library: Could not load template library from django.templatetags.mytemplate, No module named mytemplate

所以就网上查询。最终找到了一下两篇文章:

http://daily.profeth.de/2008/04/using-custom-django-template-helpers.html

http://justinworrall.com/blog/?p=389

才解决了问题。

下面大致说一下大体的做法

首先建立好你需要的模板文件,放在那里无所谓,不一定要放在templatetags目录下,随便放。

比如说例子中放在了common/templatefilters下面

内容如下:

# import the webapp module

from google.appengine.ext import webapp

# get registry, we need it to register our filter later.

register = webapp.template.create_template_register()

 

def truncate(value,maxsize,stopper = '...'):

""" truncates a string to a given maximum

size and appends the stopper if needed """

stoplen = len(stopper)

if len(value) > maxsize and maxsize > stoplen:

return value[:(maxsize-stoplen)] + stopper

else:

return value[:maxsize]

register.filter(truncate)

 

里面的truncate就是我们自定义的filter,里面可以写入想要的东西。

然后在bootstrap文件里面,写入下面两行

from google.appengine.ext import webapp

webapp.template.register_template_library( 'common.templatefilters')

 

注意,不要在模板中加入load标签,上面那一行已经将你需要的代码载入了。否则会遇到刚刚我遇到的报错。

然后就可以使用了。哈哈

评论

Thank you very much for this

Thank you very much for this information.
Good post thanks for sharing.
I like this site ;)
-----------
ps3 oyun satış ps3 oyun satış
batman batman
cam balkon cam balkon
film izle film izle
iç mimar iç mimar
çerçeve çerçeve
fizik tedavi fizik tedavi
teknoloji tasarım teknoloji tasarım
tatil tatil
film indir film indir
-----------