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. Django Settings Assignment Expressions aka Walrus Operator example by webology 3 weeks, 2 days ago
  2. codigo alto nivel by MrRocklion 2 months, 2 weeks ago
  3. Load template from specific app by Krzysiek555 3 months, 1 week ago
  4. PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
  5. "Magic Link" Management Command by webology 8 months, 2 weeks ago

Comments

Please login first before commenting.