简体   繁体   中英

Django template looping for each character

I have a text file like generated from 100 Cisco switches like this:

['device1', 'device2', 'device3', 'device4', ....., deviec100]

and I want to show this information using loop in template. So I have something like this in my HTML file to loop through each device:

{% for x in devie_list %}
{{ x }}
{% endfor %}

But it is just adding a space between each character, so the result is like this: [ ' devi c e 1 ', ' devi c e 2, .... ]

How can I tell Django, to loop through each item within the commas? or better say each list item.

Your devie_list is not a list of strings, but a string that looks like a list of strings.

You can use ast.literal_eval(…) [Python-doc] to evaluate this as a Python literal, and thus obtain a list of strings:

from ast import 

devie_list = devie_list

and thus use the result of this in the template.

You should first convert the device_list into a list data type, which you can do with any of the following methods, and then iterate on it as you wrote:

Method 1: Using python json module

import json
device_list = json.loads(device_list)

Method 2: Using eval() function

device_list = eval(device_list)

Method 3: Using string type methods

device_list = device_list.strip('[]').replace('"', '').replace(' ', '').split(',')

return this in your view or under your model:

#Your list is a string you can turn into a list like this
device_list_as_list = device_list[1:-1].split(',')

Template:

{% for x in devie_list_as_list %}
 {{ x }}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM