1

So I have a variable that is a comma separated string ("val1,val2,val3") and I want to iterate through each element in a Django template like:

{% for host in network.hosts %}
<h3>{{host}}</h3>
{% endfor %}

In this case my csv variable is network.hosts and my expected result would be:

val1

val2

val3

How would I go about doing this?

Justin Braham
  • 133
  • 4
  • 12
  • Possible duplicate of [Django templates - split string to array](https://stackoverflow.com/questions/8317537/django-templates-split-string-to-array) – Jonathan Jul 10 '17 at 20:50

2 Answers2

4

Create a custom template tag and use it. Use following code to create a new template tag for your work done.

@register.filter(name='split')
def split(value, arg):
    return value.split(arg)

Then you can use this filter in your template like following code.

{% with network.hosts|split:"," as hosts_list %}
    {% for host in hosts_list %}
     <h3>{{host}}</h3>
    {% endfor %}
{% endwith %}

Django official site will help you on creating custom template tags https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/

Chamath Sandaru
  • 412
  • 2
  • 14
  • its giving me an error, seems to not like 'split', Django Version: 1.11.2 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'split' – Justin Braham Jul 10 '17 at 20:43
0

One way of getting this to work is by defining a model in your that would allow you to split the string.

In your Python code, you could add this function to your model:

class Networks(models.Model):
    ...
    def hosts_as_list(self):
        return self.hosts.split(',')

Then your template could look like:

{% for host in network.hosts.hosts_as_list %}
    {{ host }}<br>
{% endfor %}

Hope it helps!

Source - Django templates - split string to array

cosinepenguin
  • 1,545
  • 1
  • 12
  • 21