【问题标题】:django template language if and else statement, if works but else doesn't show anythingdjango 模板语言 if 和 else 语句,if 有效但 else 不显示任何内容
【发布时间】:2016-04-11 02:45:44
【问题描述】:

这就是我想要做的。用户可以插入 url,如果该 url 是 youtube 链接,我想显示视频缩略图。(我正在使用 django-embeded-video)如果 url 不是 youtube 链接,我想要一些 ohter 图像(post.image ) 露面。所以我为此使用 else,if 语句。

 {% if post.url %}
  {% video post.url as my_video %}
  {% if my_video %}
        <img src="{{ my_video.thumbnail }}" class="img-rounded" alt="☺" height="75" width="75"/>
  {% else %}
<img src="{{post.image}}"  class="img-rounded" alt="☺" height="75" width="75"/>
  {% endif %}
{% endvideo %}
{% endif %}

使用上面的代码,当 url 是 youtube 链接时会显示视频缩略图。但是当 url 不是 youtube 链接时,什么都没有显示。

如果我这样做;

  {% if post.url %}
<img src="{{post.image}}"  class="img-rounded" alt="☺ EBAGU" height="75" width="75"/>

图片出现了……

不知道为什么“else”不起作用

Edit: img src={{post.image}} works 
img src={{my_video.thumbnail}} works
I want if img src={{my_video.thumbnail}} isn't there I want {{post.image}} to appear

【问题讨论】:

  • 您能显示video 模板标签定义吗?谢谢。
  • 您能否在这两种情况下都显示my_video 的值,因为您正在检查{% if my_video %}。您确定要通过检查此条件或作为 post.url 检查的 else 块来显示图像。
  • @AKS 对不起,我对您的问题有点困惑,您的意思是什么?我正在检查 my_video 是否存在,如果存在我想显示 x , 否则显示 y。我应该如何检查?
  • @AKS 现在我明白这两种情况的意思了,我试过 {% else my_video %} 我得到没有提供异常消息

标签: python django


【解决方案1】:

你可以试试这个:

 {% if post.url %}
   {% video post.url as my_video %}
   {% if my_video %}
       <img src="{{ my_video.thumbnail }}"/>
   {% else %}
       <img src="{{ MEDIA_URL }}{{ post.image }}"/>
       <!-- or <img src="{% static 'Path/To?You/static/image.png' %}"/> if You not upload image everytime-->
   {% endif %}
 {% endif %}

首先你需要上传post.image

【讨论】:

  • 这不起作用......我认为它不适用于上面的代码是因为图像不是视频/mp4,我认为我不需要
  • 您要运行视频还是图像?
  • 这正是我所做的,只是我不需要 {{media_url}},如上所述 显示正常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 2014-11-11
  • 2020-07-23
  • 1970-01-01
相关资源
最近更新 更多