【问题标题】:Show message when there's no excerpt - Django templates没有摘录时显示消息 - Django 模板
【发布时间】:2015-09-08 08:37:28
【问题描述】:

我在 Django 模板上有这个字段:

<p class="border_dotted_bottom">
                          {{ expert.description|slice:":300"  }}
<a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>....
</p>

如果这个对象(用户)没有“描述”(文本字段),它显示“无”这个词,我需要摆脱它,也许如果他没有“描述”,那么显示一个简单文本然后“阅读更多”

到目前为止,我已经尝试过:

        <p class="border_dotted_bottom">
            {{ % if expert.description >= 1 %}}
            {{ expert.description|slice:":300" }}
                {{% else %}}
            Éste usuario por el momento no tiene descripción
        <a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>....
         </p>

但它不起作用,我认为这只是一个错字,或者可能与我在这里使用的条件有关......

任何人都可以对此有所了解吗?

提前致谢!

【问题讨论】:

    标签: python django django-templates django-template-filters


    【解决方案1】:

    您的问题在于您的if/else 标签。你有这个:

    {{ % if ... %}}
      ...
    {{% else %}}
      ...
    

    首先,您需要用{% %} 包围if/else,而不是{{% %}}。其次,您没有endifif/else 块应如下所示:

    {% if ... %}
      ...
    {% else %}
      ...
    {% endif %}
    

    因此,您想要的块看起来像这样:

    <p class="border_dotted_bottom">
      {% if expert.description >= 1 %}
        {{ expert.description|slice:":300" }}
      {% else %}
        Éste usuario por el momento no tiene descripción
      {% endif %}
      <a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>....
    </p>
    

    话虽如此,您应该能够使用 Django 的内置 default tagdefault_if_none tag 来简化此操作,具体取决于您是否要在 expert.description 等于 ''/None 时给出默认值或者只有None:

    <p class="border_dotted_bottom">
      {{ expert.description|default:"Éste usuario por el momento no tiene descripción"|slice:":300" }}
      <a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>....
    </p>
    

    【讨论】:

    • 这成功了:' {{ Expert.description|default:"Éste usuario por el momento no tiene descripción"|slice:":300" }}'
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 2020-10-18
    • 2020-08-03
    • 1970-01-01
    • 2018-10-21
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多