简体   繁体   English

如何将 view.py 的 int 传递给 {django 模板的 for 循环}?

[英]How to pass the int of view.py to the {for loop of the django template}?

Here is the code of the template I want to pass here in the slice这是我要在切片中传递的模板的代码

<div class="swiper-container swiper-container2">
  <div class="swiper-wrapper">
  {% for category in smartphone_banners %}
    {% for product in category.product_detail_set.reverse|slice:"1:3:-1" %}
    <div class="swiper-slide py-2">
      <a href="product/{{product.name}}/{{product.id}}" style="text-decoration: none;">
        <img src="{{product.imageURL}}" alt="" style="width: 80%; margin: 0 auto;">  
        <h6 class="mt-1">{{product.name}}</h6>
        <p>{{product.price}}</p>
      </a>
    </div>
    {% endfor %}
  {% endfor %}
  </div>
</div>

I want to replace slice:"1:3:-1" %} by something like slice:"1:totalnu:-1" %} or slice:"1:{{totalnu}}:-1" %} , but both ways are not working.我想用 slice: slice:"1:totalnu:-1" %}slice:"1:{{totalnu}}:-1" %}类的东西替换slice:"1:3:-1" %} %} ,但是两种方式都行不通。

How can I pass the value of totalnu ?如何传递totalnu的值? Here is my code from views.py :这是我的views.py代码:

        for i in smartphone_banners: 
        for pr in i.product_detail_set.reverse()[1:3:-1]:
            print(pr)
            print(totalnu)
            totalnu = totalnu + 1 
    print(totalnu)
    lists = []
    for ifn in smartphone_banners:
        for prf in ifn.product_detail_set.reverse()[(totalnu - 2):totalnu:-1]:
            print( 'this is the fonal.', prf)

Call the render() method of the Template object with a given set of variables (context).使用给定的一组变量(上下文)调用模板 object 的 render() 方法。
A Context is similar to a dictionary.上下文类似于字典。
Create context containing variables include totalnu from the views.py .创建包含变量的上下文,包括来自views.py的 totalnu。

context = { 'totalnu': totalnu }上下文 = { 'totalnu': totalnu }

You should have this render(request, template, context) in your views.py你应该在你的views.py中有这个render(request, template, context)
In your template use {{ totalnu }} to pass the value of totalnu在您的模板中使用{{ totalnu }}传递 totalnu 的值

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

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