简体   繁体   English

Django 模板循环每个字符

[英]Django template looping for each character

I have a text file like generated from 100 Cisco switches like this:我有一个从 100 个 Cisco 交换机生成的文本文件,如下所示:

['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:所以我在我的 HTML 文件中有这样的东西来循环遍历每个设备:

{% 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, .... ]但它只是在每个字符之间添加一个空格,所以结果是这样的: [ ' devi c e 1 ', ' devi c e 2, .... ]

How can I tell Django, to loop through each item within the commas?如何告诉 Django 遍历逗号内的每个项目? 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.您的devie_list不是字符串列表,而是看起来像字符串列表的字符串。

You can use ast.literal_eval(…) [Python-doc] to evaluate this as a Python literal, and thus obtain a list of strings:您可以使用ast.literal_eval(…) [Python-doc]将其评估为 Python 文字,从而获得字符串列表:

from ast import literal_eval

devie_list = literal_eval(devie_list)

and thus use the result of this in the template.因此在模板中使用 this 的结果。

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:您应该首先将device_list转换为列表数据类型,您可以使用以下任何方法执行此操作,然后在编写时对其进行迭代:

Method 1: Using python json module方法一:使用python json模块

import json
device_list = json.loads(device_list)

Method 2: Using eval() function方法二:使用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:在您的视图中或在您的 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 %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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