Package pytils :: Package templatetags :: Module pytils_numeral
[hide private]

Source Code for Module pytils.templatetags.pytils_numeral

  1  # -*- coding: utf-8 -*- 
  2  # -*- test-case-name: pytils.test.templatetags.test_numeral -*- 
  3  # PyTils - simple processing for russian strings 
  4  # Copyright (C) 2006-2007  Yury Yurevich 
  5  # 
  6  # http://gorod-omsk.ru/blog/pythy/projects/pytils/ 
  7  # 
  8  # This program is free software; you can redistribute it and/or 
  9  # modify it under the terms of the GNU General Public License 
 10  # as published by the Free Software Foundation, version 2 
 11  # of the License. 
 12  # 
 13  # This program is distributed in the hope that it will be useful, 
 14  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 15  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 16  # GNU General Public License for more details. 
 17  """ 
 18  pytils.numeral templatetags for Django web-framework 
 19  """ 
 20   
 21  __id__ = __revision__ = "$Id: pytils_numeral.py 70 2007-02-19 03:42:32Z the.pythy $" 
 22  __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_numeral.py $" 
 23   
 24  from django import template, conf 
 25  from pytils import numeral, utils 
 26   
 27  register = template.Library()  #: Django template tag/filter registrator 
 28  encoding = conf.settings.DEFAULT_CHARSET  #: Current charset (sets in Django project's settings) 
 29  debug = conf.settings.DEBUG  #: Debug mode (sets in Django project's settings) 
 30  show_value = getattr(conf.settings, 'PYTILS_SHOW_VALUES_ON_ERROR', False)  #: Show values on errors (sets in Django project's settings) 
 31   
 32  # Если отладка, то показываем 'unknown+сообщение об ошибке'. 
 33  # Если отладка выключена, то можно чтобы при ошибках показывалось 
 34  # значение, переданное фильтру (PYTILS_SHOW_VALUES_ON_ERROR=True) 
 35  # либо пустая строка. 
 36   
 37  if debug: 
 38      default_value = "unknown: %(error)s" 
 39      default_uvalue = u"unknown: %(error)s" 
 40  elif show_value: 
 41      default_value = "%(value)s" 
 42      default_uvalue = u"%(value)s" 
 43  else: 
 44      default_value = "" 
 45      default_uvalue = u"" 
 46       
 47  # -- filters 
 48   
49 -def choose_plural(amount, variants):
50 """ 51 Choose proper form for plural. 52 53 Value is a amount, parameters are forms of noun. 54 Forms are variants for 1, 2, 5 nouns. It may be tuple 55 of elements, or string where variants separates each other 56 by comma. 57 58 Examples:: 59 {{ some_int|choose_plural:"пример,примера,примеров" }} 60 """ 61 try: 62 if isinstance(variants, str): 63 uvariants = utils.provide_unicode(variants, encoding, default_value) 64 else: 65 uvariants = [utils.provide_unicode(v, encoding, default_uvalue) for v in variants] 66 res = utils.provide_str( 67 numeral.choose_plural(amount, uvariants), 68 encoding, 69 default=default_value 70 ) 71 except Exception, err: 72 # because filter must die silently 73 try: 74 default_variant = variants 75 except Exception: 76 default_variant = "" 77 res = default_value % {'error': err, 'value': default_variant} 78 return res
79
80 -def rubles(amount, zero_for_kopeck=False):
81 """Converts float value to in-words representation (for money)""" 82 try: 83 res = utils.provide_str( 84 numeral.rubles(amount, zero_for_kopeck), 85 encoding, 86 default=default_value 87 ) 88 except Exception, err: 89 # because filter must die silently 90 res = default_value % {'error': err, 'value': str(amount)} 91 return res
92
93 -def in_words(amount, gender=None):
94 """ 95 In-words representation of amount. 96 97 Parameter is a gender: MALE, FEMALE or NEUTER 98 99 Examples:: 100 {{ some_int|in_words }} 101 {{ some_other_int|in_words:FEMALE }} 102 """ 103 try: 104 res = utils.provide_str( 105 numeral.in_words(amount, getattr(numeral, str(gender), None)), 106 encoding, 107 default=default_value 108 ) 109 except Exception, err: 110 # because filter must die silently 111 res = default_value % {'error': err, 'value': str(amount)} 112 return res
113 114 # -- register filters 115 116 register.filter('choose_plural', choose_plural) 117 register.filter('rubles', rubles) 118 register.filter('in_words', in_words) 119 120 # -- tags 121
122 -def sum_string(amount, gender, items):
123 """ 124 in_words and choose_plural in a one flask 125 Makes in-words representation of value with 126 choosing correct form of noun. 127 128 First parameter is an amount of objects. Second is a 129 gender (MALE, FEMALE, NEUTER). Third is a variants 130 of forms for object name. 131 132 Examples:: 133 {% sum_string some_int MALE "пример,примера,примеров" %} 134 {% sum_string some_other_int FEMALE "задача,задачи,задач" %} 135 """ 136 try: 137 uitems = [utils.provide_unicode(i, encoding, default_uvalue) for i in items] 138 res = utils.provide_str( 139 numeral.sum_string(amount, getattr(numeral, str(gender), None), uitems), 140 encoding, 141 default=default_value 142 ) 143 except Exception, err: 144 # because tag's renderer must die silently 145 res = default_value % {'error': err, 'value': str(amount)} 146 return res
147 148 # -- register tags 149 150 register.simple_tag(sum_string) 151