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

2024-04-23 13:47:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试添加一个在django模板的个人资料图像的评论后。。。如果模型中没有配置文件图像,那么我想用样式化的文本代替图像。但我担心的是如何告诉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,但在模板中出现错误。。。我该怎么处理这个?你知道吗


Tags: django图像image模板imgforifwith
1条回答
网友
1楼 · 发布于 2024-04-23 13:47:49

模板标记未正确关闭。另请参考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 %}

相关问题 更多 >