javascript - 具有动态内容的 html 中的树结构
问题描述
我有来自数据库的数据,查询执行格式如下
[(‘Country-1’, ‘state1’), (‘Country-1’, ‘state2’), (‘Country-1’, ‘state3’),
(‘Country-2’, ‘state1’), (‘Country-2’, ‘state2’), (‘Country-2’, ‘state3’),
(‘Country-3’, ‘state1’), (‘Country-3’, ‘state2’), (‘Country-3’, ‘state3’)]
我想将此结果集转换为以下格式
context = {
'countries': [ { 'Countryname': 'country1’,
'state': [ { 'Statename': 'state1'},
{'Statename': 'state2'},
{'Statename': 'state3'} ]
},
{ 'Countryname': 'country2’,
'state': [ { 'Statename': 'state1'},
{'Statename': 'state2'},
{'Statename': 'state3'} ]
},
{ 'Countryname': 'country3’,
'state': [ { 'Statename': 'state1'},
{'Statename': 'state2'},
{'Statename': 'state3'} ]
}
]
}
这样我就可以在 Django 中迭代 HTML 中的数据以创建树格式:
<ul class = "myUL">
{% for country in data %}
<li class = "caret"> {{ country.countryname }} </li>
<ul class="nested">
{% for state in country.statename %}
<li>{{state.statename}}</li>
{% endfor %}
</ul>
{% endfor %}
HTML 的预期输出为:
Country-1
State1
State2
State3
Country -2
State1
State2
State3
Country -3
State1
State2
State3
解决方案
尝试以下操作:
数据解析器:
data = [('Country-1', 'state1'), ('Country-1', 'state2'), ('Country-1', 'state3'), ('Country-2', 'state1'), ('Country-2', 'state2'), ('Country-2', 'state3'), ('Country-3', 'state1'), ('Country-3', 'state2'), ('Country-3', 'state3')]
reformatted_data = {}
for pair in data:
state_list = reformatted_data.get(pair[0], None)
if state_list:
if pair[1] in state_list:
pass
else:
reformatted_data[pair[0]].append(pair[1])
else:
reformatted_data[pair[0]] = [pair[1]]
# Try this print in your console to make sure it's working properly
print(reformatted_data)
显示数据的模板:
<ul class = "myUL">
{% for country, statelist in data.items %}
<li class = "caret"> {{ country }} </li>
<ul class="nested">
{% for state in statelist %}
<li>{{ state }}</li>
{% endfor %}
</ul>
{% endfor %}
推荐阅读
- shell - 使用 golang 将命令行的输入读入 shell 脚本 exec
- javascript - 从附件列表中读取文件数据后,无法在 .zip 文件中创建文件夹
- angularjs - 在 IE 11 中,ng-repeat 中的项目在一秒钟左右后消失?
- reactjs - 我应该更新特定组件的减速器状态还是在组件状态下管理?
- javascript - 基于现有对象/数组创建一个空对象/数组
- performance - 臃肿的 CacheStorage 会减慢 Service Worker 的响应速度吗?
- r - 将跨行列标题添加到 knitr kable 表
- git - 使用 Git 的“交叉分支”
- c# - 如何在 .Net Core API 中禁用静态文件功能?
- google-apps-script - 可以使用 GAS 创建交互式 Web 应用程序吗?