Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass template variable to slice filter in Django templates

I'm trying to slice loop in django template with variable

USUAL WAY

{% for article in module.module_article_key.module_article_category.article_category_key.all|slice:":2" %}
    {{ article.article_title }}
{% endfor %}

WHAT NEEDS

{% for article in module.module_article_key.module_article_category.article_category_key.all|slice:":module.module_article_key.module_article_count" %}
    {{ article.article_title }}
{% endfor %}

so we have working variable {{ module.module_article_key.module_article_count }}

normaly this variable gives integer value stored for this module, however wen i use it to slice loop - nothing happens

like image 609
ilyas Jumadurdyew Avatar asked Jan 27 '23 21:01

ilyas Jumadurdyew


1 Answers

You need to cast module_article_count to string first then making articleSlice via nested {% with %} and use the resulting template variable in slice filter as follow:

{% with  articleCount=module.module_article_key.module_article_count|stringformat:"s" %}
    {% with  articleSlice=":"|add:articleCount %}
        {% for article in module.module_article_key.module_article_category.article_category_key.all|slice:articleSlice %}
            {{ article.article_title }}
        {% endfor %}
    {% endwith %}
{% endwith %}
like image 141
mrehan Avatar answered Jan 30 '23 11:01

mrehan