Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate forloop.counter to a string in my django template

Tags:

I am already trying to concatenate like this:

{% for choice in choice_dict %}
    {% if choice =='2' %}
        {% with "mod"|add:forloop.counter|add:".html" as template %}
            {% include template %}
        {% endwith %}                   
    {% endif %}
{% endfor %}    

but for some reason I am only getting "mod.html" and not the forloop.counter number. Does anyone have any idea what is going on and what I can do to fix this issue? Thanks alot!

like image 230
Ethan Avatar asked Apr 20 '11 05:04

Ethan


People also ask

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.


1 Answers

Your problem is that the forloop.counter is an integer and you are using the add template filter which will behave properly if you pass it all strings or all integers, but not a mix.

One way to work around this is:

{% for x in some_list %}
    {% with y=forloop.counter|stringformat:"s" %}
    {% with template="mod"|add:y|add:".html" %}
        <p>{{ template }}</p>
    {% endwith %}
    {% endwith %}
{% endfor %}

which results in:

<p>mod1.html</p>
<p>mod2.html</p>
<p>mod3.html</p>
<p>mod4.html</p>
<p>mod5.html</p>
<p>mod6.html</p>
...

The second with tag is required because stringformat tag is implemented with an automatically prepended %. To get around this you can create a custom filter. I use something similar to this:

http://djangosnippets.org/snippets/393/

save the snipped as some_app/templatetags/some_name.py

from django import template

register = template.Library()

def format(value, arg):
    """
    Alters default filter "stringformat" to not add the % at the front,
    so the variable can be placed anywhere in the string.
    """
    try:
        if value:
            return (unicode(arg)) % value
        else:
            return u''
    except (ValueError, TypeError):
        return u''
register.filter('format', format)

in template:

{% load some_name.py %}

{% for x in some_list %}
    {% with template=forloop.counter|format:"mod%s.html" %}
        <p>{{ template }}</p>
    {% endwith %}
{% endfor %}
like image 87
dting Avatar answered Sep 28 '22 02:09

dting