如何修复JavaScript模板字面量中for循环不生效,渲染Django查询集为Bootstrap表格下拉框问题
问题修正方案
你当前的代码存在3个核心错误:
- 后端传递的Django QuerySet直接通过
{{ Publisher }}渲染到JS中是纯字符串,无法直接遍历 - 模板字面量仅支持嵌入表达式,不支持直接写入
for循环这类语句,需要提前生成循环后的HTML片段再拼接 - 原有option的value和显示值写死,没有取publisher的实际数据,选中判断逻辑也错误
步骤1:调整后端数据传递逻辑
修改view.py,将QuerySet序列化为纯列表方便前端解析:
def view_material(request): # 只取publisher的名称字段转为普通列表,也可根据需求保留id等字段 query_results_publisher = list(Publisher.objects.values_list('name', flat=True)) return render(request, 'material/index.html', context={'Publisher':query_results_publisher})
步骤2:修正前端模板与JS逻辑
修改index.html的相关代码,首先安全注入publisher数组,再重写renderPublisher函数:
... <th class ='publisher' data-field="book.publisher" data-formatter="renderPublisher">Publisher</th> ... <!-- 用Django的json_script过滤器安全注入JSON数据,避免XSS风险 --> {{ Publisher|json_script:"publisher-data" }} <script> // 从注入的script标签中读取publisher数组 const Publisher = JSON.parse(document.getElementById('publisher-data').textContent); function renderPublisher(value) { // 先生成所有option的HTML片段 let optionHtml = ''; for (const pub of Publisher) { // 遍历判断当前publisher是否匹配传入的value,选中对应项 const selected = value === pub ? 'selected' : ''; optionHtml += `<option value="${pub}" ${selected}>${pub}</option>`; } // 把生成的option片段拼入select的模板字符串中 return ` <select style="width: 7em" name="" id=""> ${optionHtml} </select> `; } </script>
额外说明
如果需要保留publisher的id作为option的value,只需要把后端查询改为values('id', 'name'),前端遍历的时候取pub.id和pub.name即可。
内容的提问来源于stack exchange,提问作者django
相关产品推荐
相关产品推荐

