【问题标题】:jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got 'item'jinja2.exceptions.TemplateSyntaxError: 预期标记 \'语句块结束\',得到 \'item\'
【发布时间】:2022-12-18 11:56:06
【问题描述】:

我试图在表格品牌中显示状态为绿色或红色,但我收到此错误: jinja2.exceptions.TemplateSyntaxError:预期标记“语句块结束”,得到“项目”

<table class="table table-hover">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">Brands</th>
          <th scope="col">Status</th>
        </tr>
      </thead>
      <tbody>
        {% for item in data %}
        <tr>
          <th scope="row">1</th>
          <td>{{item.brand}}</td>
          {% if item.decommissed==False %}
          <td><i class="bi-check-circle-fill" style="color:green"></i></td>
          {% else item.decommissed==True %}
          <td><i class="bi bi-x-circle-fill" style="color:red"></i></td>
          {% endif %}
        </tr>
        {% endfor %}
      </tbody>
    </table>

【问题讨论】:

    标签: python flask


    【解决方案1】:

    您不能将条件传递给您的 {% else %} 标签。如果您从标签中删除 item.decommissed==True,它应该可以使用以下代码:

    <table class="table table-hover">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">Brands</th>
          <th scope="col">Status</th>
        </tr>
      </thead>
      <tbody>
        {% for item in data %}
        <tr>
          <th scope="row">1</th>
          <td>{{item.brand}}</td>
          {% if item.decommissed==False %}
          <td><i class="bi-check-circle-fill" style="color:green"></i></td>
          {% else %}
          <td><i class="bi bi-x-circle-fill" style="color:red"></i></td>
          {% endif %}
        </tr>
        {% endfor %}
      </tbody>
    </table>
    

    作为替代方案,您还可以在 Jinja2 模板中使用 elif 子句而不是 else 子句。 elif 子句允许您在执行最终的 else 子句之前指定要检查的其他条件。以下是如何在代码中使用 elif 子句的示例:

    <table class="table table-hover">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">Brands</th>
          <th scope="col">Status</th>
        </tr>
      </thead>
      <tbody>
        {% for item in data %}
        <tr>
          <th scope="row">1</th>
          <td>{{item.brand}}</td>
          {% if item.decommissed==False %}
          <td><i class="bi-check-circle-fill" style="color:green"></i></td>
          {% elif item.decommissed==True %}
          <td><i class="bi-exclamation-circle-fill" style="color:yellow"></i></td>
          {% else %}
          <td><i class="bi bi-x-circle-fill" style="color:red"></i></td>
          {% endif %}
        </tr>
        {% endfor %}
      </tbody>
    </table>
    

    请注意,在检查布尔值时,elif 没有多大意义。但这可能对其他类型有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2019-02-11
      • 1970-01-01
      • 2022-09-22
      相关资源
      最近更新 更多