You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板if语句内图标重复渲染问题咨询

问题:Key-Value模型实现静态模板动态化时图标重复渲染

背景代码

模型代码

class SiteDataKeyValue(models.Model):
    key = models.CharField(max_length=200, verbose_name="Text title")
    value = models.TextField(verbose_name="Text")

    def __str__(self):
        return self.key

视图代码

class ContactUsPageView(ListView):

    """In this view we are fetching site data from database, in a function named get_context_data.
    In this function, we filter the model for objects that contains the word 'contact', therefore
    fetching data referring to the about page only. After that the context list is sent to the
    template, and there with a for loop and an if statement, each key, value set is chosen for the proper place.
    """

    model = SiteDataKeyValue
    template_name: str = "core/contact-us.html"

    def get_context_data(self, **kwargs):
        context = super(ContactUsPageView, self).get_context_data(**kwargs)
        context["contact_page_data"] = self.model.objects.filter(key__contains="contact")
        return context

模板代码

{% for text in contact_page_data  %}
    {% if text.key == "contact us factory address" %}
        <p class="card-text"><i class="bi bi-geo-alt me-2">
            {{ text.value }}
        </p>
    {% endif %}
 {% endfor %}

问题现象

数据库中仅存在一条key为contact us factory address的数据,但模板渲染时,<i class="bi bi-geo-alt me-2">图标被重复渲染11次(11为视图传递的含“contact”的总数据量),而对应的值仅显示一次。

解决方法

为<i>标签添加闭合标签</i>后,问题得到解决,其余代码无错误。修改后的模板代码片段如下:

{% for text in contact_page_data  %}
    {% if text.key == "contact us factory address" %}
        <p class="card-text"><i class="bi bi-geo-alt me-2"></i>
            {{ text.value }}
        </p>
    {% endif %}
 {% endfor %}

内容的提问来源于stack exchange,提问作者Vahid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:25:24