【问题标题】:Efficient way to pass list to template for bootstrap grid将列表传递给引导网格模板的有效方法
【发布时间】:2019-08-09 08:08:33
【问题描述】:

将数据从路由传递到模板以不破坏模板的最佳做法是什么?

我有一个使用 N 行乘 3 列的引导网格的模板。

目前我正在计算路线所需的行数,并将列表传递给模板以使用 Jinja2 进行迭代。我这样做是因为我似乎无法在模板中导入Math,或者执行一些基本的python 操作,例如len(mylist)

由于这个“hack”,我必须使用3*row + i 来识别元素。 它有效,但这种硬编码触发了我的强迫症!

能否有更多经验丰富的开发人员分享您会为此类情况做些什么?

@app.route('grid')
def grid():
    items = Items.query.all()
    items_row = list(range(0, ceil(len(items)/3) )) # Because I cannot round-up on Jinja2
    ...

return render_template('grid.html', items=items, item_rows=item_rows)
{% for row in item_rows %}

{% if 3*row + 0 < items|length %}
    <div class="row">
        <div class="col-lg-4">
            <a href="{{ url_for('item', id=items[3*row + 0].id) }}"
                <h1>{{ items[3*row + 0].header }}</h1>
            </a>
            <a href="{{ url_for('item', id=items[3*row + 0].id) }}"
                <p>{{ items[3*row + 0].body }}</p>
            </a>
        </div>
   </div>
{% endif %}

{% if 3*row + 1 < items|length %}
    <div class="row">
        <div class="col-lg-4">
            <a href="{{ url_for('item', id=items[3*row + 1].id) }}"
                <h1>{{ items[3*row + 1].header }}</h1>
            </a>
            <a href="{{ url_for('item', id=items[3*row + 1].id) }}"
                <p>{{ items[3*row + 1].body }}</p>
            </a>
        </div>
    </div>
{% endif %}


{% if 3*row + 2 < items|length %}
    <div class="row">
        <div class="col-lg-4">
            <a href="{{ url_for('item', id=items[3*row + 2].id) }}"
                <h1>{{ items[3*row + 2].header }}</h1>
            </a>
            <a href="{{ url_for('item', id=items[3*row + 2].id) }}"
                <p>{{ items[3*row + 2].body }}</p>
            </a>
        </div>
    </div>
{% endif %}

【问题讨论】:

  • 我希望 thisthis 有所帮助
  • 检查一下@kellymandem
  • @Yelle 进展如何?
  • @kellymandem 我浏览了文档,不确定如何在我的上下文中使用Set,但数学部分真的很有帮助。我在 FOR 循环下发现了一些特殊变量,例如 loop.index()loop.length,看起来很有希望!感谢指点(:

标签: flask bootstrap-4 jinja2


【解决方案1】:

我已经重构了我的代码:

  • 现在更简洁了
  • 阅读/理解也更加困难
{% set rows = 3 %}
{% set cols = 3 %}

{% for item in items %}

    {% if loop.index0 // rows != (loop.index0 - 1) // rows %}
        <div class="row">
    {% endif %}

        <div class="col-lg-4 col-md-6 col-sm-12 col-xs-12">
            <a href="{{ url_for('item.html', id=item.id) }}">
                <h1>{{ item.header }}<h1>
            </a>
            <p>{{ item.body }}</p>
        </div>

    {% if loop.index0 % cols  == 2 %}
        </div>
    {% endif %}

{% endfor %}

【讨论】:

    猜你喜欢
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2012-09-27
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多