【问题标题】:Django nested if statement giving me a strange errorDjango嵌套if语句给了我一个奇怪的错误
【发布时间】:2021-09-20 01:51:41
【问题描述】:

我有 2 个彼此相邻的 if 语句来检查用户是否正在关注另一个用户。当我尝试关闭两个 if 语句时,我遇到了一个奇怪的错误。我在页面的顶部和底部有一个块内容和结束块。我还有一个加载人性化标签。我试图添加一个 endblock 标签,并尝试重新洗牌。我有点卡住了,但我知道我忘记了一些东西。有谁能帮帮我吗?

这里是代码

{% extends 'core/base.html' %} {% load humanize %} {% block content %}
<div class="container">
  <div class="columns">
    <div class="column is-12">
      <h1 class="title">{{ request.user.username }}</h1>
      <p>Followers: {{ user.foxyprofile.followed_by.count }}</p>
      <p>Follows {{ user.foxyprofile.follows.count }}</p>
      {% if user != request.user %} {% if request.user.foxyprofile in
      user.foxyprofile.followed_by.all %}
      <a href="{% url 'unfollow_foxy' user.username %}" class="button is-danger"
        >Unfollow</a
      >
      {% else %}
      <a href="{% url 'follow_foxy' user.username %}" class="button is-success"
        >Follow {{ user.username}}</a
      >
      {% endif %} {% endif %}
    </div>
  </div>
  <div class="columns">
    <div class="column is-8">
      <div class="wrapper-fox">
        {% for fox in user.foxs.all %}
        <div class="fox">
          <p class="name">{{ fox.created_by.username }}</p>
          <p>{{ fox.body }}</p>
          <p class="info">{{ fox.created_at|naturaltime}}</p>
          <hr />
          {% endfor %}
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

我遇到的错误...

第 17 行的块标记无效:“endif”,预期为“endblock”。您是否忘记注册或加载此标签?

【问题讨论】:

  • 还显示您开始和结束块的代码部分。
  • @ShivendraPratapKushwaha 我添加了全部内容!
  • user 通常总是request.user 除非 user 在上下文中指定。但我们看不到那部分。
  • 你可以在这里找到答案stackoverflow.com/questions/36528958/…>
  • @AaronCloud:您不应该在第二个if 语句中添加换行符,标签在单个行上完全指定。

标签: django if-statement


【解决方案1】:

您不应该在第二个if 语句中添加换行符,标签在单个 行上完全指定。这意味着{% if … %} tags [Django-doc] 看起来像:

{% if user != request.user %}
    {% if request.user.foxyprofile in user.foxyprofile.followed_by.all %}
        …
    {% else %}
        …
    {% endif %}
{% endif %}

或者你把两个{% if … %}标签放在同一行:

{% if user != request.user %}{% if request.user.foxyprofile in user.foxyprofile.followed_by.all %}
        …
{% else %}
        …
{% endif %}{% endif %}

您还可以将{% if … %}s 写在两行上,将两个{% endif %} 写在同一行上。唯一不允许的是在模板文件中将标签拆分为多行。

在 Django 中,模板解析器不能处理多行的模板标签,或者至少在撰写本文时不能。

【讨论】:

  • 谢谢@Willem Van Onsem,我相信就是这样。它现在正在工作!多么奇怪,但它会像那样对行敏感是有道理的。
  • @AaronCloud:好吧,我对 Django 的模板引擎不太满意。它有一定的特性,例如用于模板过滤器的管道字符 (|) 之前/之后的空格,我认为它没有“正式”规范在解析空格/新行。我同意这确实是实施得不太好的事情之一。
猜你喜欢
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多