简体   繁体   English

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

[英]how to declare a variable in django template and change the value of that variable in if condition?

I'm trying to add a profile image in django template for comments for the post... If profile image is not there in the model then I want to replace with the styled text in place of Image. 我正在尝试在django模板中添加个人资料图片,以便为帖子添加评论...如果模型中没有个人资料图片,那么我想用样式文本替换Image。 But I'm getting worried about how to tell the django template that if image exists or not... 但是我担心如何告诉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 -->

In the above code I have tried to create a variable img using 'with' but getting error in template... What should I do with this? 在上面的代码中,我尝试使用'with'创建一个变量img,但是模板中出现错误...该怎么办?

Template tags are not closing properly. 模板标签未正确关闭。 Please refer to docs Also, improved code a bit. 请同时参考文档 ,改进代码。

<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 %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM