如何在Django模板中声明变量并在if条件下更改该变量的值?

时间:2019-03-04 19:01:49

标签: python django django-templates

我正在尝试在django模板中添加个人资料图片,以便为帖子添加评论...如果模型中没有个人资料图片,那么我想用带样式的文本代替Image。但是我担心如何告诉django模板是否存在图像...

<div class="comment-author">
{% for image in profile %}
    {% if image.profile|slugify == comment.author %}
        {% with "exist" as img %} <!-- if image exist create img variable -->
        <img src="{{ image.profileImg.url }}" alt="{{ image.profile }}">
    {% endif %}
{% endfor %}
{% if not img %} <!-- using img variable for checking -->
    <span class="userImg"><b>{{ comment.author|make_list|slice:':2'|join:'' }}</b></span>
{% endif %}
{% endwith %} <!-- closing the with statement -->

在上面的代码中,我尝试使用'with'创建变量img,但模板中出现错误...该怎么办?

1 个答案:

答案 0 :(得分:0)

模板标记未正确关闭。另请参阅docs,改进代码。

<div class="comment-author">
{% for image in profile %}
    {% if image.profile|slugify == comment.author %}
        {% with "exist" as img %} <!-- if image exist create img variable -->
        <img src="{{ image.profileImg.url }}" alt="{{ image.profile }}">

{% else %} <!-- using img variable for checking -->
    <span class="userImg"><b>{{ comment.author|make_list|slice:':2'|join:'' }}</b></span>
{% endif %}

{% endwith %} <!-- closing the with statement -->
{% endfor %}