Django模板 - 新变量声明 [英] Django Template - New Variable Declaration

查看:85
本文介绍了Django模板 - 新变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我前言我只是启动Python,所以如果这真的是一个简单的问题^ _ ^

Let me preface by I am just starting Python so if this is really a simple question ^_^

我有一个html文件与以下内容: p>

I have a html file with the following content:

        {%for d in results%}
        <div class="twt">
            <img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span>
            <span class="date">{{ d.created_at }}</span>
        </div>
    {% endfor %}

哪个工作很好,但我也想声明一个变量在这个页面上让我们来看看这个例子,我们可以将RowNumber放在每个d显示的地方,然后吐出当前的RowNumber。

which works well but I also would like to declare a variable on this page. Let's say for this example, we can it RowNumber which will increment for each d displayed, spitting out the current RowNumber.

我尝试过:

{{ RowNumber = 0}} 
{{ RowNumber ++ }}

但是似乎不允许我声明RowNumber。

But it doesn't seem to allow me to declare RowNumber.

推荐答案

p>查看<$ c $的文档 c> for loop。

Check out the documentation on the for loop.

它会自动创建一个名为 forloop.counter 的变量持有当前的迭代索引。

It automatically creates a variable called forloop.counter that holds the current iteration index.

就如何声明变量的更大问题来说,Django没有现成的方法,它不被认为是一个缺失的功能,但功能。如果你真的想这样做,可以通过自定义标签,但在大多数情况下,您想要遵循的哲学主要是要做的任何事情都应该在视图中完成,并且模板应该保留用于非常简单的逻辑。举个例子,总结一下,你可以使用添加过滤器。同样,您可以创建自己的过滤器就像标签一样。

As far as the greater question on how to declare variables, there is no out-of-the-box way of doing this with Django, and it is not considered a missing feature but a feature. If you really wanted to do this it is possible with custom tags but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic. For your example of summing up a total, for example, you could use the add filter. Likewise, you can create your own filters just like with tags.

这篇关于Django模板 - 新变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆