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

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

问题描述

让我先介绍一下我刚刚开始使用 Python,所以如果这真的是一个简单的问题 ^_^

我有一个包含以下内容的 html 文件:

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

{% 结束为 %}

效果很好,但我也想在此页面上声明一个变量.假设在这个例子中,我们可以使用 RowNumber,它会随着显示的每个 d 递增,吐出当前的 RowNumber.

我尝试过:

{{ RowNumber = 0}}{{ 行号 ++ }}

但它似乎不允许我声明 RowNumber.

解决方案

查看 for 循环中的noreferrer">文档.

它会自动创建一个名为 forloop.counter 的变量来保存当前的迭代索引.

至于如何声明变量的更大问题,在 Django 中没有现成的方法可以做到这一点,它不被认为是一个缺失的特性,而是一个特性.如果您真的想这样做,可以使用 自定义标签 但在大多数情况下,您想要遵循的理念是,您想要做的大部分事情都应该在视图中完成,并且模板应该保留用于非常简单的逻辑.例如,对于汇总总数的示例,您可以使用 添加过滤器.同样,您可以创建自己的过滤器 就像标签一样.

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

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

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.

I tried doing:

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

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

解决方案

Check out the documentation on the for loop.

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

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天全站免登陆