{% extends 'portfolio/base.html' %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<title>{% block title %}Blog{% endblock %}</title>
</head>
<body>
{% block content %}
<div class="container text-center">
<h2>Blogs</h2>
<h2>PyPatriot has posted {{ blogs.count }} Blog{{ blogs.count | pluralize }}</h2>
<div class="row">
<div class="col-sm-6">
{% for blog in blogs %}
<div class="card" style="width: 18rem;">
<img src="{{ blog.cover_photo.url }}" class="card-img-top" width="230" height="230">
<div class="card-body">
<h4 class="card-title">{{ blog.title }}</h4>
<h6>{{ blog.date | date:'M d Y'}}</h6>
<p class="card-text">{{ blog.description | truncatechars:70 }}</p>
<a href="{% url 'blog:detail' blog.id %}" class="btn btn-primary">View</a>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
</body>
</html>
应使用forloop.counter
对卡片进行计数
这是我网站的一部分
{% for post in object_list %}
{% if forloop.counter0|divisibleby:3 %} <div class="row"> {% endif %}
<div class="col-md-4">
<div class="card article">
<a href="{{ post.get_absolute_url }}"><img class="responsive opacity" src="{{ post.img_url }}" alt=""></a>
<div class="card-content">
<p class="date-field">{{ post.created_on|date:"d.m.y" }} / {{post.field}}</p>
<h2 class="article-title"><a class="link-article" href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
<div class="content">
{{ post.content|safe|truncatewords:35 }}
</div>
<div class="button-wrapper"><a href="{{ post.get_absolute_url }}"><button class="button button1" >Czytaj dalej</button></a></div>
</div>
</div>
</div>
{% if forloop.counter|divisibleby:3 or forloop.last %}</div><br>{% endif %}
{% endfor %}
它将在一行中创建3张紧挨着的卡片。
如果希望每行创建更多或更少卡片,则需要更改 在您的例子中,它看起来像:If forloop.counter0DivisibleBy:3
中的DivisibleBy
以及<div class="container text-center">
<h2>Blogs</h2>
<h2>PyPatriot has posted {{ blogs.count }} Blog{{ blogs.count | pluralize }}</h2>
{% for blog in blogs %}
{% if forloop.counter0|divisibleby:3 %} <div class="row"> {% endif %}
<div class="col-sm-4">
<div class="card" style="width: 18rem;">
<img src="{{ blog.cover_photo.url }}" class="card-img-top" width="230" height="230">
<div class="card-body">
<h4 class="card-title">{{ blog.title }}</h4>
<h6>{{ blog.date | date:'M d Y'}}</h6>
<p class="card-text">{{ blog.description | truncatechars:70 }}</p>
<a href="{% url 'blog:detail' blog.id %}" class="btn btn-primary">View</a>
</div>
</div>
{% if forloop.counter|divisibleby:3 or forloop.last %}</div><br>{% endif %}
{% endfor %}