Python 如何在Django模板中增加变量?

Python 如何在Django模板中增加变量?,python,django,Python,Django,我正在制作一个网格,需要声明变量并增加它 {% for new, des, i, link, published, author in mylist %} {% if x == 1 %} <div class="col-md-6"> <div class="h-100 mt-2 row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md

我正在制作一个网格,需要声明变量并增加它

{% for new, des, i, link, published, author in mylist %}
    {% if x == 1 %}
        <div class="col-md-6">
            <div class="h-100 mt-2 row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
                <div class="col p-4 d-flex flex-column position-static">
                    <strong class="d-inline-block mb-2 text-primary">World</strong>
                    <h5 class="mb-0">{{new}}</h5>
                    <div class="mb-1 text-muted">{{published}}</div>
                    <p class="card-text mb-auto">{{des}}</p>
                    <a href="{{link}}" class="stretched-link">Continue reading</a>
                </div>
                <div class="col-auto d-none d-lg-block">
                    <img class="bd-placeholder-img" src="{{i}}" width="200" height="250" >
                </div>
            </div>
        </div>
    {% endif %}
{% endfor %}
{%for new,des,i,link,published,作者在mylist%}
{%x==1%}
World
{{new}}
{{published}}

{{des}

{%endif%} {%endfor%}
帮助我声明变量x并在模板中像
x+1
那样递增它

我尝试了
{%x=0%}
但是没有用

尝试下面的方法:

{% set x = 0 %}
{% for new, des, i, link, published, author in mylist %}
    {% set x = x + 1 %}
    {% if x == 1 %}
        <div class="col-md-6">
            <div class="h-100 mt-2 row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
                <div class="col p-4 d-flex flex-column position-static">
                    <strong class="d-inline-block mb-2 text-primary">World</strong>
                    <h5 class="mb-0">{{new}}</h5>
                    <div class="mb-1 text-muted">{{published}}</div>
                    <p class="card-text mb-auto">{{des}}</p>
                    <a href="{{link}}" class="stretched-link">Continue reading</a>
                </div>
                <div class="col-auto d-none d-lg-block">
                    <img class="bd-placeholder-img" src="{{i}}" width="200" height="250" >
                </div>
            </div>
        </div>
    {% endif %}
{% endfor %}
{%set x=0%}
{%表示新建、des、i、链接、已发布、作者在mylist%}
{%set x=x+1%}
{%x==1%}
World
{{new}}
{{published}}

{{des}

{%endif%} {%endfor%}
django有一个{{forloop.counter}}。您可以使用它。

您不能在模板中声明变量并增加它。您确实可以访问for循环中的
forloop.counter
。@schwobasegll如果您能告诉我如何代替
{%if x==1%}
就好了,只要使用
{%if forloop.counter==1%}
。您还有
forloop.counter0
,它是一个基于0的计数器。签出除了
forloop.counter
,还设置了许多其他变量-例如
forloop.first
是一个布尔值,指示这是否是循环的第一次迭代,通常用于写标题行之类的事情,就像您在这里尝试做的那样<代码>{%if-forloop.first%}应该这样做,比检查计数器更简洁。。查看文档以获取完整列表:@schwobaseggl感谢此方法运行良好。来自评论:嗨,这篇文章似乎没有为这个问题提供答案。请编辑您的答案并加以改进,或者将其作为问题/其他答案的注释发布。Pycharm说的是
未解决的“set”标记
如何修复?