Login

joinstrings filter

Author:
Tomek
Posted:
November 22, 2010
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

In one situation I needed to join strings in template, so I wrote this filter.

Use it like this:

1)

var = 23

{{"I have eat %d apples today."|joinstrings:var}}

-> "I have eat 23 apples today."

var = '23'

{{"I have eat %s apples today."|joinstrings:var}}

-> "I have eat 23 apples today."

2)

var = [23, 45] #or any iterable object (except string - see pt. 1)

{{"I have eat %d apples and %d pears today."|joinstrings:var}}

-> "I have eat 23 apples and 45 pears today."

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@register.filter
def joinstrings(string_format, string_arguments):
    '''Template filters that perform string joins.
    
       Examples:
       1)
       var = '23'
       {{"I have eat %s apples today."|joinstrings:var}} -> "I have eat 23 apples today."
       
       2)
       var = [23, 45]   #or any iterable object (except string - see pt. 1) 
       {{"I have eat %d apples and %d pears today."|joinstrings:var}} -> "I have eat 23 apples and 45 pears today."

       3)
       It works even like that:
       var = 'Mouses'
       {% with 'My cat eat 5 %s today'|joinstrings:var|lower as info %}
        {{info}}
       {% endwith %}
    '''
    
    try:
        if hasattr(string_arguments, '__iter__'):
            return string_format%tuple(string_arguments)
        else:
            return string_format%string_arguments
    except:
        return string_format

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.