【问题标题】:Is there a way to programmatically have 4 cards per row?有没有办法以编程方式每行有 4 张卡?
【发布时间】:2019-11-28 20:13:56
【问题描述】:

我目前正在使用 Python Flask 和 Bootstrap。 我希望得到它,这样如果一行中有 4 张卡,它将自动创建一个新行。

我刚刚遇到的问题是,我拥有的帖子越多,行卡就越长越薄。 当前代码:

 {% extends "base.html" %}
{% block content %}
    <div class="card-deck">
        {# Go through each forum post #}
        {% for post in forum_posts.items %}

            <div class="card">
                <div class="card-body">
                    <span class="badge badge-info">{{ post.cat }}</span>

                    <h3 class="card-title"><a class="card-title"
                                              href="{{ url_for('forum_posts.view_post', forum_post_id=post.id) }}">{{ post.title }}</a>
                    </h3>
                    <h6 class="card-subtitle mb-2 text-muted">Written by: {{ post.author.username }}</h6>
                    <p>{{ post.text[:100] }}...</p>
                </div>
                <div class="card-footer">
                    <a href="{{ url_for('forum_posts.view_post', forum_post_id=post.id) }}"
                       class="btn btn-primary">Read
                        Blog Post</a>
                </div>
            </div>

        {% endfor %}
    </div>

{% endblock %}

【问题讨论】:

    标签: python-3.x flask bootstrap-4 flask-wtforms


    【解决方案1】:

    您可以在 python 端对此进行编码,以便在 jinja2 中使用数组数组更容易:

    >>> arr = [0,1,2,3,4,.....,102]
    >>> forum_posts.items = []
    >>> for i in range(int(len(arr)/4)):
            j = i * 4
            forum_posts.items.append([arr[j], arr[j+1], arr[j+2], arr[j+3]])
            # needs an error trap for IndexError on 103
    

    然后在jinja2中:可以双循环:

    {% for row in forum_posts.items %}
        {% for item in row %}
             {# HTML here for a new row of at most 4 cards #}
    

    有一种方法可以在 jinja2 中使用可变循环计数器并设置新行 HTML,例如,如果新循环索引是 4 的精确倍数:

    {% for i, post in enumerate(forum_posts.items) %}
        {% if i % 4 == 0 %}
            {# new row code #}
        {% else %}
            {# regular row code %}
        {% endif %}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-02
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2012-03-16
      • 2011-11-22
      • 2016-03-04
      相关资源
      最近更新 更多