Is there an equivalent django pattern of 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 like a filter {% "Hello"|multiply:"5" %}

Or maybe "re" control of the circuit? Sort of:

 {% repeat 5 %} Hello {% endrepeat %} 

I can write a filter or tag myself, but wondered if I could save some problems.

If someone could argue that there are no built-in features like I require, this would be a perfectly acceptable answer.

+6
source share
2 answers

There are no built-in features that you need.

This will be a trivial tag to make for yourself - there are some useful examples in the Django docs.

I suppose you could hack something using something like {% for x in "12345" %}Hello{% endfor %} , but it's a terrible hack.

+3
source

Here is another hack:

 {% for x in ""|ljust:"100" %} Hello World! {% endfor %} 

I use an empty string as the value here, and I repeat the 100x thing. You can also use a variable to determine the number of repetitions using this hack :) just replace "100" with the variable.

 {% for x in ""|ljust:repeat_count %} Hello World! {% endfor %} 

Or make your own ...

you can make a filter with several filters pretty easy ( more about creating your own tags and template filters ):

In the installed application (for example, included in the INSTALLED_APPS setting) add the module "templatetags" and a file named "string_multiply.py"

So you will have something like this:

 your_app + templatetags | + __init__.py | + string_multiply.py + __init__.py + models.py 

plus everything you have in your application ...

Here is your string_multiply.py

 from django.template import Library register = Library() @register.filter def multiply(string, times): return string * times 

Yes, that all this ...

And then in your template

 {% load string_multiply %} Chris Brown: {% filter multiply:3 %} Yeah! {% endfilter %} You (x5): {{ request.user.username|multiply:5 }} 

Output Result:

 Chris Brown: Yeah! Yeah! Yeah! You (x5): Koliber ServicesKoliber ServicesKoliber ServicesKoliber ServicesKoliber Services 
+16
source

Source: https://habr.com/ru/post/903919/


All Articles