[Fixed]-Django slice numbers in template

42👍

There is a the “slice” template tag

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#slice

It uses the same syntax as Python’s list slicing.

Example:

{{ some_list|slice:":2" }}

in python this is equivalent to:

some_list[:2]

BTW your 2nd example would be "2:5" not "2,5"

NB. Python slicing works on any ‘sequence’. Strings and lists are sequences. Numbers are not!

6👍

any extra filter that converts the number into a string before slicing will work. I used these variants:

{{ some_num|slugify|slice:"2:5" }}

and

{{ some_num|stringformat:"d"|slice:"5:10" }}

3👍

{{1234567|make_list|slice:'2:5'|join:''}}

Stefano’s answer is on the right track. You need a pre-processing step to turn your number into a list, and a post-processing step to merge that list back into string.

0👍

You just need to write code as follow for slicing :-
{{valueformoney|slice:"0:4"}}

{% for cloth in valueformoney|slice:"0:4" %}
    <div class="product h-100  w-100 border rounded ">
        <div class="img__container">
            <img src="{{cloth.cloth_image.url}}" alt="" />
        </div>
        <div class="product__bottom">
            <div class="price">
                <span class="text-danger"> <del>{% min_price cloth as result %} {{ result|rupee}}</del></span>&nbsp;
                <span>{% discount_price cloth as result %}{{result|rupee}}</span>
                <span class="float-right badge p-3 badge-info">Save {{cloth.cloth_discount}}% </span>
            </div>
            <h3 class="p-4">{{cloth.cloth_name}}</h3>
            <div class="button">
                <a href="/product_detail/{{cloth.cloth_slug}}" class="btn-block">See More</a>
            </div>
        </div>
    </div>
{% endfor %}

Leave a comment