【问题标题】:Returning Python Dictionary on multiple line in HTML with Flask使用 Flask 在 HTML 中的多行上返回 Python 字典
【发布时间】:2021-05-17 18:19:09
【问题描述】:

我在将字典返回到 python 中的多行时遇到问题。字典以节目名称作为键,然后以概要作为值,我想将其格式化为节目的标题出现在一行,然后是概要在下一行。

    @app.route('/rec/', methods=['GET','POST'])
def rec():
    if request.method == "POST":
        animes = openAnimes()
        usr_input = request.form['animeChoice']
        amnt = request.form['howMany']

        try:
            whatisearched = whatwelike(animes, usr_input)['Title']

        except :
            return render_template('rec.html')
            
        try:
            yourDic = run(usr_input, amnt)
            return render_template("result.html", title = whatisearched, rec = yourDic)
        except :
            return render_template('rec.html')

usr_input 获取用户输入的显示,amnt 是程序返回的数量。 yourDic 后端的 python 函数返回的内容,它是一个带有 show(key) 和它的 synopsis(value) 的字典。 这是 HTML:

{% extends "rec.html" %}

{% block title %}Recommendation Page{% endblock %}

{% block content %}
<body>
    <h1>If you liked <span style="color: black">{{title}}</span> you should watch:</h1>
    <br>
    <br>

    {{rec}}

    
</body>


{% endblock %}

{{rec}} 是我想多行返回的内容。

非常感谢。

编辑: 我找到了一个解决方案,尽管它不允许我在 for 循环中使用用户输入变量作为我的范围的值,这是我的代码。

<h1 style='margin-left:10px'>If you liked <span style="color: black">{{title}}</span> you should watch:</h1>
    <br>
    <br>
    <ol style=' margin-left:10px; color:black'>
    {%for i in range(0, 5)%} 
        <li style = 'color:black; font-size:26px; margin-left:20px'><a href="{{rec[i]['Link']}}" style='text-decoration:none'>{{rec[i]['Title']}}</a></li>
        <br>
        <p style='font-size:18px'>{{rec[i]['Synopsis']}}</p>
        <br>
        
    {%endfor%}
    </ol>

【问题讨论】:

    标签: python html css flask web


    【解决方案1】:

    创建一个 HTML 表格或定义列表,或者只使用一个 break 标记并分别通过 rec["show"]rec["synopsis"] 访问 rec 的内容。

    另见Rendering a python dict in Jinja2 / Werkzeug

    【讨论】:

    • 非常感谢,参考帮助很大,尽管如果我将其放入列表中,我似乎无法在 for 循环中使用用户输入变量作为范围值。
    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2018-10-29
    • 2016-07-05
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2016-08-18
    相关资源
    最近更新 更多