Django模板循环中联系信息重复显示问题求助
解决文本重复显示的问题
你现在的问题根源在于那段联系文本是放在for循环内部的if判断里——只要有一个city满足author.access_challenge条件,就会输出一次文本,多个符合条件的city就会导致文本重复显示。要让它只出现一次,我们需要把判断逻辑移到循环外面,先确认是否存在符合条件的city,再决定是否显示文本。
第一步:修改视图函数,添加判断变量
在视图里,我们可以用any()函数快速判断是否有至少一个city满足限制条件,然后把这个结果传到模板上下文:
def cities(request, pk): country = Post.objects.get(id=pk).country cities = Post.objects.filter(country=country).distinct('city') # 新增:判断是否存在受访问限制的城市 has_access_restriction = any(city.author.access_challenge for city in cities) context = { 'cities': cities, 'country': country, 'has_access_restriction': has_access_restriction # 将判断结果传入模板 } return render(request, 'users/cities.html', context)
第二步:调整HTML模板的文本输出位置
把原来循环内的联系文本移到循环外面,根据新的变量has_access_restriction控制显示;循环内部只处理不受限制城市的表格渲染:
{% if has_access_restriction %} <p class="small text-center"> In order to get information about this contact us through almaz@protonmail.com </p> {% endif %} {% for city in cities %} {% if not city.author.access_challenge %} <table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;"> <tbody> <tr> <td><a class="text-uppercase" href="{% url 'users:address' city.pk %}">{{ city.city }}</a></td> </tr> </tbody> </table> {% endif %} {% endfor %}
这样修改后,不管有多少个受限制的城市,联系文本只会显示一次;同时不受限制的城市会正常渲染对应的表格。
如果你的需求是当所有城市都受限制时才显示文本,且不渲染任何表格,可以把视图里的any()换成all(),并调整模板结构:
视图修改:
has_access_restriction = all(city.author.access_challenge for city in cities)
模板修改:
{% if has_access_restriction %} <p class="small text-center"> In order to get information about this contact us through almaz@protonmail.com </p> {% else %} {% for city in cities %} {% if not city.author.access_challenge %} <table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;"> <tbody> <tr> <td><a class="text-uppercase" href="{% url 'users:address' city.pk %}">{{ city.city }}</a></td> </tr> </tbody> </table> {% endif %} {% endfor %} {% endif %}
内容的提问来源于stack exchange,提问作者Almaz
相关产品推荐
相关产品推荐

