Ticket #11687: add_filter.diff

File add_filter.diff, 2.6 KB (added by Filip Gruszczyński, 15 years ago)

coercing to int, then ducktyping + tests + docs

  • django/template/defaultfilters.py

     
    649649
    650650def add(value, arg):
    651651    """Adds the arg to the value."""
    652     return int(value) + int(arg)
     652    try:
     653        return int(value) + int(arg)
     654    except (ValueError, TypeError):
     655        try:
     656            return value + arg
     657        except:
     658            return value
    653659add.is_safe = False
    654660
    655661def get_digit(value, arg):
  • tests/regressiontests/templates/filters.py

     
    326326        'date02': (r'{{ d|date }}', {'d': datetime(2008, 1, 1)}, 'Jan. 1, 2008'),
    327327        #Ticket 9520: Make sure |date doesn't blow up on non-dates
    328328        'date03': (r'{{ d|date:"m" }}', {'d': 'fail_string'}, ''),
     329       
     330         # base tests for add that assert, that old behaviour, which means
     331         # trying to add two values as ints, is kept
     332         'add01': (r'{{ i|add:"5" }}', {'i': 2000}, '2005'),
     333         'add02': (r'{{ i|add:"napis" }}', {'i': 2000}, '2000'),
     334         'add03': (r'{{ i|add:16 }}', {'i': 'not_an_int'}, 'not_an_int'),
     335         'add04': (r'{{ i|add:"16" }}', {'i': 'not_an_int'}, 'not_an_int16'),
     336         # further additions using dynamic typing
     337         'add05': (r'{{ l1|add:l2 }}', {'l1': [1, 2], 'l2': [3, 4]}, '[1, 2, 3, 4]'),
     338         'add06': (r'{{ t1|add:t2 }}', {'t1': (3, 4), 't2': (1, 2)}, '(3, 4, 1, 2)'),
     339         'add07': (r'{{ d|add:t }}', {'d': date(2000, 1, 1), 't': timedelta(10)}, '2000-01-11'),
    329340    }
  • docs/ref/templates/builtins.txt

     
    858858
    859859If ``value`` is ``4``, then the output will be ``6``.
    860860
     861.. versionadded:: 1.2
     862
     863At first filter tries to add two values coerced into integers and if this fails, it adds those two values using duck typing.
     864
     865For example:
     866
     867    {{ first_list|add:second_list }}
     868   
     869If ``first_list`` is ``[1, 2, 3]`` and ``second_list`` is ``[4, 5, 6]``, then the output will be ``[1, 2, 3, 4, 5, 6]``.
     870
     871Keep in mind, that for two strings, that can be coerced to integer, it will return a sum, rather than
     872a concatenation, as in the first example.
     873
    861874.. templatefilter:: addslashes
    862875
    863876addslashes
Back to Top