Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a django template equivalent of the python string multiplication function?

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.

like image 425
Krystian Cybulski Avatar asked Dec 16 '11 16:12

Krystian Cybulski


2 Answers

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 %}

Or make your own...

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...

Here's your string_multiply.py

from django.template import Library

register = Library()

@register.filter
def multiply(string, times):
    return string * times

Yup that's the whole thing...

And then in your template

{% 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
like image 66
Jiaaro Avatar answered Sep 23 '22 21:09

Jiaaro


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.

like image 26
Dan Breen Avatar answered Sep 21 '22 21:09

Dan Breen