templatetagをつくってみる
自分でdjangoのtemplatetagsを作ってみた。
数字の3桁区切りをやりたかったのでlocale.formatを使うフィルターを書いてみた。
myproject/app/templatetags に __init__.pyとlocaleformat.pyを配置。__init__.pyは空ファイル。
from django import template
import locale
register = template.Library()
@register.filter
def localeformat(num):
locale.setlocale(locale.LC_NUMERIC,'ja_JP.utf-8')
return locale.format("%d", num, True)
ロケールが決め打ちなのは気にしないように。ドキュメント通りです。注意しなければならないのはINSTALLED_APPSに書いてないとtemplatetagsの下を見に行きません。
ソースを読んだところ django.templatetags の中で検索パスを書き直しているのがわかった。つまりですねー、django.templatetagsというパッケージ名があったら実ファイルパス(/usr/lib/python/django/template)に内部で対応させているわけですが、それに /path/to/myproject/app/templatetags のファイルパスも見てねと追加しているんだなと。はは、そういうふうにloadを隠蔽しているわけですか。

Debian QA
Facebook (taniguchi.takaki)
Twitter (@takaki_t)