【问题标题】:How can I restructure my code for rendering in jinja 2 template?如何重构我的代码以在 jinja 2 模板中呈现?
【发布时间】:2019-09-16 14:20:21
【问题描述】:

我正在尝试在 Web 应用程序中显示来自 mongo 数据库的值。我正在使用烧瓶框架,我正在调用函数,该函数将返回列表以在 html 模板中打印。我的代码如下

dic = mycol.find(myquery)

这将内容字典对象从 mongodatabase 查询

当我遍历这个对象时,我得到了字典集

for x in dic:

x 的每个值都包含

{'name':'john','age':'15','weight':'50'}
{'name':'ash','age':'18','weight':'60'}
{'name':'tim','age':'20','weight':'80'}

我用于呈现这些值的代码如下

person_name = []
person_age = []
person_weight = []
for x in dic:
    person_name.append(x["person_name"])
    person_age.append(x["person_age"]) 
    person_weight.append(x["person_weight"])

稍后我将返回这些列表以在 html 中打印 jinja 2 代码如下

{{person_name[loop.index0]}} {{person_age[loop.index0]}} {{person_weight[loop.index0]}}

我觉得这样做不是更好的方法。那么有没有其他更好的方法可以在几行代码中做到这一点?感谢阅读

【问题讨论】:

  • 我不知道你为什么要重组它。为什么不直接将原始字典列表传递给模板?

标签: python html python-3.x mongodb jinja2


【解决方案1】:

如果您使用的是烧瓶,您可以简单地使用 render_template() 烧瓶函数将列表或字典传递给 HTML 模板。

在你的情况下,你可以简单地做(以此为例)。注意,dictionary=dic 写在哪里,第一个 dictionary 可以是任何名称/变量,然后您将在 Jinja2 语法中引用。

@app.route('/')
def index():
    # Code to get dictionary from db, assigned to dic like yours
    return render_template('[name of template].html', dictionary=dic)

然后在您的模板中,您可以使用 Jinja2 语法进行 for 循环以列出 dic 字典/列表。

// Somewhere inside HTML template
{% for x in dictionary %}
    <p>{{ x.name }}</p>
    <p>{{ x.age }}</p>
    <p>{{ x.weight }}</p>
{% endfor %}

【讨论】:

    猜你喜欢
    • 2013-05-09
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多