In python I can write "Hello" * 5
and get
HelloHelloHelloHelloHello
Is there a way to do this in a django template? Something like {% multiply "Hello" 5 %}
or as a filter {% "Hello"|multiply:"5" %}
Or maybe a "repeat" loop control? Something like:
{% repeat 5 %}
Hello
{% endrepeat %}
I can write a filter or tag myself, but was wondering if I could save myself some trouble.
If someone can authoritatively say that there is no built-in capability such as I require, that would be a perfectly acceptable answer.
Here's another hack:
{% for x in ""|ljust:"100" %}
Hello World!
{% endfor %}
I'm using an empty string as the value here, and I repeat the thing 100x. You can also use a variable to determine the number of repeats with this hack :) just replace "100" with the variable.
{% for x in ""|ljust:repeat_count %}
Hello World!
{% endfor %}
you can make the multiply filter quite easily (more on making your own template tags and filters):
In an installed app (e.g., included in your INSTALLED_APPS setting), add a "templatetags" module and a file called "string_multiply.py"
So you will have something like this:
your_app
+ templatetags
| + __init__.py
| + string_multiply.py
+ __init__.py
+ models.py
plus whatever else you have in your app...
from django.template import Library
register = Library()
@register.filter
def multiply(string, times):
return string * times
Yup that's the whole thing...
{% load string_multiply %}
Chris Brown:
{% filter multiply:3 %}
Yeah!
{% endfilter %}
You (x5):
{{ request.user.username|multiply:5 }}
The output of which will be:
Chris Brown:
Yeah!
Yeah!
Yeah!
You (x5):
Koliber ServicesKoliber ServicesKoliber ServicesKoliber ServicesKoliber Services
There is no built-in capability such as you require.
That would be a trivial tag to make for yourself - there are some helpful examples in the Django docs.
I suppose you could hack something together by using something like {% for x in "12345" %}Hello{% endfor %}
but that is a horrible hack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With