Flask模板如何实现分两列独立for循环 解决链接异常嵌套问题
两列独立循环的链接覆盖异常排查
问题根源
该异常和Flask模板的循环逻辑无关,本质是HTML标签未闭合引发的浏览器解析错位。
检查你模板中第一列的Live Ads循环代码:
{% for ad in ads %} <a href="{{ url_for('ads', image_key = ad.image_key, posts = ad.image_key)}}">{{ad.title}} {% endfor %}
这段代码在每次循环时都开启了<a>超链接标签,但始终没有书写对应的闭合标签</a>。
浏览器在解析这类未闭合的行内标签时,会自动将后续相邻的所有DOM节点都纳入这个标签的作用范围,直到遇到同级别的明确闭合标签为止。这就是为什么第一列最后一个广告(示例中的Broccoli)的链接,会顺着DOM结构一直覆盖到第二列的Previous Ads标题、甚至后续所有页面内容的原因。
同时你第二列的Previous Ads循环也存在标签闭合顺序错误的隐患:
{% for inactive_ad in inactive_ads %} <dt><a href="{{ url_for('ads', image_key = inactive_ad.image_key, posts = inactive_ad.image_key)}}">{{inactive_ad.title}}</dt> {% endfor %}
这里<a>标签没有在</dt>标签之前闭合,后续同样可能出现链接覆盖范围超标的问题。
修正后的可用代码
在循环体内部补全所有未闭合的标签,保证标签开启、闭合的层级和顺序完全对应即可解决问题:
{% extends "layout.html" %} {% block main %} <form action="{{ url_for('searched') }}" method="post"> <div class="form-group"> <input placeholder="Search food" type ="search" name="search"/> <button class="btn btn-success" type="submit" name="action"><span class="glyphicon glyphicon-search"></span></button> </div> </form> <div class="row"> <div class="column"> <h2>Live Ads</h2> <dl class="desc-info" style="text-indent: 15%"> {% for ad in ads %} <a href="{{ url_for('ads', image_key = ad.image_key, posts = ad.image_key)}}">{{ ad.title }}</a> {% endfor %} </dl> </div> <div class="column"> <h2>Previous Ads</h2> <dl class="desc-info" style="text-indent: 15%"> {% for inactive_ad in inactive_ads %} <dt> <a href="{{ url_for('ads', image_key = inactive_ad.image_key, posts = inactive_ad.image_key)}}">{{ inactive_ad.title }}</a> </dt> {% endfor %} </dl> </div> </div> {% endblock %}
同类问题排查技巧
- 遇到这类渲染错位问题时,优先在浏览器中查看实际输出的页面源码,不要只盯着模板代码排查——浏览器的自动纠错逻辑经常会拉长未闭合标签的影响范围,很容易误导排查方向
- 编写循环内的HTML结构时,要保证在单次循环体内就完成一对标签的完整开启和闭合,不要把闭合标签放到循环外部,否则一旦循环次数和标签数量不匹配,就会出现解析错位
内容的提问来源于stack exchange,提问作者DataDan
相关产品推荐
相关产品推荐

