0

I am newbie in django. How can I concat string in a for loop in django template

{% for lead in project.leaders %}
    {% if forloop.counter == 1 %}
        {% lead_member = lead.0 %}
     {% else %}
        {% lead_member = ','.lead.0 %}
     {% endif %}
{{ lead_member }}
{% endfor %}

Finally my lead_member should be test1,test2,test3....

what is happening now (my current code)

 {% for lead in project.leaders %}
    {{ lead.0}}
 {% endfor %}

and the output is test1test2test3.... but i want to make same as test1,test2,test3....

Rejoanul Alam
  • 5,435
  • 3
  • 39
  • 68
  • In what language would this make sense? You can't assign in Django templates, but even if you could, repeatedly assigning to the same variable wouldn't create a list. And you don't have any commas anywhere, which was supposed to be the whole point of the question. – Daniel Roseman Sep 17 '15 at 19:13
  • check now my question revised. this is demo code. I want to achieve that what mentioned in last line – Rejoanul Alam Sep 17 '15 at 19:15
  • Why do you need to concat at all? the template is just rendering a html page so the output will be the same – Sayse Sep 17 '15 at 19:19
  • @Sayse again question revised. please check now – Rejoanul Alam Sep 17 '15 at 19:23
  • @Sayse your solution will concat extra `comma` if there are only one data. Somewhat confused and couldn't understand what is unclear in my question?? I just want to concat a comma after each data – Rejoanul Alam Sep 17 '15 at 19:27

2 Answers2

8

Try this. it works

{% for lead in project.leaders %}
    {{ lead.0 }}{% if not forloop.last %}, {% endif %}
{% endfor %}

There's no need to assign anything, nor do you need that type of complexity by using assignment tags. To keep your templating stupid-simple, you could always do this in your view, or even at the model level:

# don't step on the `join` built-in
from django.template.defaultfilters import join as join_filter

class Project(models.Model):

    @property
    def leaders(self):
        return join_filter(self.objects.values_list('some_field', flat=True), ', ')

Then all you have to do in the template is:

{{ project.leaders }}
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
0

It's hard to understand your question, but I hope i did it. There is a number of related questions such as String-concatination, How to concatenate in django

It's possible to create first string, concatinate it with comma and new string for every iteration. You are also able to make smth like ','.join(list_of_strings) on your server side before rendering. You can also join your list in templating by {{ list|join:", " }}.

Community
  • 1
  • 1
yavalvas
  • 330
  • 2
  • 17