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://www.pyobject.ru/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 102 2007-07-12 12:33:36Z the.pythy $" 
 22  __url__ = "$URL: https://pythy.googlecode.com/svn/tags/pytils/0_2_2/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 get_plural(amount, variants):
81 """ 82 Get proper form for plural and it value. 83 84 Value is a amount, parameters are forms of noun. 85 Forms are variants for 1, 2, 5 nouns. It may be tuple 86 of elements, or string where variants separates each other 87 by comma. You can append 'absence variant' after all over variants 88 89 Examples:: 90 {{ some_int|get_plural:"пример,примера,примеров,нет примеров" }} 91 """ 92 try: 93 if isinstance(variants, str): 94 uvariants = utils.provide_unicode(variants, encoding, default_value) 95 else: 96 uvariants = [utils.provide_unicode(v, encoding, default_uvalue) for v in variants] 97 res = utils.provide_str( 98 numeral._get_plural_legacy(amount, uvariants), 99 encoding, 100 default=default_value 101 ) 102 except Exception, err: 103 # because filter must die silently 104 try: 105 default_variant = variants 106 except Exception: 107 default_variant = "" 108 res = default_value % {'error': err, 'value': default_variant} 109 return res
110
111 -def rubles(amount, zero_for_kopeck=False):
112 """Converts float value to in-words representation (for money)""" 113 try: 114 res = utils.provide_str( 115 numeral.rubles(amount, zero_for_kopeck), 116 encoding, 117 default=default_value 118 ) 119 except Exception, err: 120 # because filter must die silently 121 res = default_value % {'error': err, 'value': str(amount)} 122 return res
123
124 -def in_words(amount, gender=None):
125 """ 126 In-words representation of amount. 127 128 Parameter is a gender: MALE, FEMALE or NEUTER 129 130 Examples:: 131 {{ some_int|in_words }} 132 {{ some_other_int|in_words:FEMALE }} 133 """ 134 try: 135 res = utils.provide_str( 136 numeral.in_words(amount, getattr(numeral, str(gender), None)), 137 encoding, 138 default=default_value 139 ) 140 except Exception, err: 141 # because filter must die silently 142 res = default_value % {'error': err, 'value': str(amount)} 143 return res
144 145 # -- register filters 146 147 register.filter('choose_plural', choose_plural) 148 register.filter('get_plural', get_plural) 149 register.filter('rubles', rubles) 150 register.filter('in_words', in_words) 151 152 # -- tags 153
154 -def sum_string(amount, gender, items):
155 """ 156 in_words and choose_plural in a one flask 157 Makes in-words representation of value with 158 choosing correct form of noun. 159 160 First parameter is an amount of objects. Second is a 161 gender (MALE, FEMALE, NEUTER). Third is a variants 162 of forms for object name. 163 164 Examples:: 165 {% sum_string some_int MALE "пример,примера,примеров" %} 166 {% sum_string some_other_int FEMALE "задача,задачи,задач" %} 167 """ 168 try: 169 if isinstance(items, str): 170 uitems = utils.provide_unicode(items, encoding, default_uvalue) 171 else: 172 uitems = [utils.provide_unicode(i, encoding, default_uvalue) for i in items] 173 res = utils.provide_str( 174 numeral.sum_string(amount, getattr(numeral, str(gender), None), uitems), 175 encoding, 176 default=default_value 177 ) 178 except Exception, err: 179 # because tag's renderer must die silently 180 res = default_value % {'error': err, 'value': str(amount)} 181 return res
182 183 # -- register tags 184 185 register.simple_tag(sum_string) 186