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