Pythonanywhere - 返回多行文本

时间:2017-06-14 13:38:03

标签: python html flask pythonanywhere

我正在使用这段代码(大部分时间,因为它每次都不同)会打印多行字符串。

if request.method == "POST":
    d = {'Dirt 4': g_dirt4, 'Destiny 2': g_destiny2, 'South Park: The Fractured but Whole': g_southpark, 'Call of Duty: WWII': g_codww2, 'Star Wars Battlefront II': g_bfront2, 'Red Dead Redemption 2': g_reddead2, 'FIFA 18': g_fifa18, 'MotoGP™17': g_motogp17, 'The Elder Scrolls Online: Morrowind': g_elderscrolls, 'Crash Bandicoot N. Sane Trilogy': g_crashbandicoot}

    max_value = max(d.values())
    maximal_keys = [ k for k,v in d.items() if v==max_value ]
    for title in maximal_keys:
        print (title)

    return render_template("result_page.html", title=title)

因此,这意味着,当您单击按钮时,它将返回result_page.html,并且在html代码中,title变量将替换为实际标题。 所以这是html代码:

<body>
    This game(s) belongs to you: {{ title }}
</body>

当python代码打印出来时,它看起来像这样,但就像我说的那样,它有时会有所不同:

2017-06-14 07:08:22 Destiny 2
2017-06-14 07:08:22 Call of Duty: WWII

问题在于,当我在这种情况下单击按钮时,它只会将标题更改为Destiny 2.我不会像我想要的那样获得多行标题。我该怎么做?

所以现在在这种情况下它会告诉我:

https://i.gyazo.com/30c4afc6434c811b958804aad505137e.png

但我想看到这个:

https://i.gyazo.com/ee523d9d1dd6a28ba095e4fcfd8203ab.png

3 个答案:

答案 0 :(得分:1)

您当前的html模板并不真正支持打印多个元素,您的代码也只返回一个要渲染的标题。

您应该检查这个与您的问题类似的其他问题:How to build up a HTML table with a simple for loop in Jinja2?

你应该得到这样的东西:

"

答案 1 :(得分:0)

您希望您的模板&#34;迭代某些内容&#34;

在您的模板中,代码必须如下所示:

<body>
{% for t in list_of_titles %}
 <p>- {{ t }}</p>
{% endfor %}
</body>

你需要传递一些东西来迭代你的路线功能,例如标题列表。

return render_template('result_page.html', list_of_titles=list_of_titles)

问:您想一次显示所有标题,还是想在按下按钮后添加一个标题?

评论后编辑:

您的list_of_titles必须看起来像

list_of_titles = ['MotoGP', 'Dirt']

答案 2 :(得分:0)

感谢Anup,回答的问题是:

return render_template("result_page.html", title=maximal_keys)

<ul> {% for n in title %} <li>{{n}}</li> {% endfor %} </ul> 

这给了我这个:

https://i.gyazo.com/2e41a4ea8d852dc4f14a7aa02979bd2d.png

根据评论@Update:

     <li>
        <div class=”text”>
           <h1>{{ n }}</h1>
        </div>
        <div class=”image”>
           <img src=”{{ img_path }}”>
        </div>            
     </li>