ほんじゃらねっと

ダイエット中プログラマのブログ

djangoのテンプレートで使うカスタムフィルタを追加する

マニュアルを読めば書いてあるけど、覚書き。
http://michilu.com/django/doc-ja/templates_python/


以前作成した(というかコピーした)、数値を3桁区切りにする関数を
djangoテンプレート上でフィルタとして利用できるようにする。


testproject/utils.py

...
def moneyfmt(value, places=2, curr='', sep=',', dp='.', pos='', neg='-', trailneg=''):
...
# 中身は http://www.m-takagi.org/docs/python/lib/decimal-recipes.html 参照
...


testproject/main/templatetags/extra_filters.py

from django import template
from testproject import utils
register = template.Library()
@register.filter
def moneyfmt(value):
if len(str(value)) > 0:
return utils.moneyfmt(Decimal(str(value)), 0, dp='')
else:
return value

アプリケーションフォルダ内のtemplatetagsフォルダにフィルタ用ファイルを
入れるとそのアプリケーションのテンプレートで読み込めるようになるらしい。


testproject/main/templates/test.html

...
{% load extra_filters %}
{{ kingaku|moneyfmt }} <!-- kingakuの値が3桁カンマ区切りで表示される -->
...