簡體   English   中英

django技術實現按帖子數換行

[英]Django technology implementation of line breaks by number of posts

我的問題

我正在使用 Django,Bootstrap 制作購物中心

我想在帖子變成4的時候實現技術換行

我想如果我使用 col-3 和 {$ for %} {% endfor %} 它將分為四個和換行符。 但不工作

我該如何解決?

我的模特

from django.db import models

class Cloth(models.Model):
    title = models.CharField(max_length=30)
    explain = models.CharField(max_length=30)
    price = models.IntegerField(blank=True)

    def __str__(self):
        return self.title

我的看法

from django.shortcuts import render
from .models import Cloth

def index(request):
    post = Cloth.objects.all()
    return render(request, 'Blog/index.html', {'post':post})

我的網址

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),

]

我的 index.html

<div class="container py-3">
    <h2 align="center"> Top </h2>
</div>
<div class="container py-2 px-1">
    <div class="row">
        {% for p in post %}
        <div class="card col-3" style="width: 16rem;">
            <img src="http://placeimg.com/600/600/any" class="card-img-top" alt="...">
            <div class="card-body">
                <h5 class="card-title"> {{ p.title }}</h5>
                <p class="card-text"> {{ p.explain }}</p>
                <p> {{ p.price }}</p>
            </div>
        </div>
        {% endfor %}
    </div>

問題是您將所有內容都放入一個單行 div 中。

您可以使用 divisibleby 和 forloop.counter 來測試記錄號是否是四的倍數,如果是,則關閉您的行 div 並在模板中打開另一個。 有關這些模板工具的更多詳細信息,請參閱 文檔

索引.html

<div class="container py-2 px-1">
    <div class="row">
        {% for p in post %}
        <div class="card col-3" style="width: 16rem;">
            <img src="http://placeimg.com/600/600/any" class="card-img-top" alt="...">
            <div class="card-body">
                <h5 class="card-title"> {{ p.title }}</h5>
                <p class="card-text"> {{ p.explain }}</p>
                <p> {{ p.price }}</p>
            </div>
        </div>


        {% if forloop.counter|divisibleby:"4" %}
    <!-- here we close the row and then reopen another -->
    </div>
    <div class="row">
        {% endif %}

        {% endfor %}
    </div>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM