如何在flas中使用for循环显示json数据

2024-09-29 21:47:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾尝试使用flask在HTML中显示JSON数据,使用{% for bring in company %} ... {% endfor %}循环,没有成功。但是,我将JSON应用到关于.html使用数据/名称为的直接应用程序的页面,例如:{{races[0][name]}},它可以工作。我不知道有什么问题

我甚至试图找到它,但没有找到任何解决办法。你知道吗

Python/烧瓶

import os
import json
from flask import Flask, render_template
app = Flask(__name__)


@app.route("/")
def index():
    return render_template("index.html")

@app.route('/about')
def about():
    data = []
    with open("data/races.json", "r") as json_data:
        data = json.load(json_data)
    return render_template("about.html", page_title="About", races=data)

@app.route("/contact")
def contact():
    return render_template("contact.html", page_title="Contact")

@app.route("/careers")
def careers():
    return render_template("careers.html", page_title="Careers")


if __name__ == "__main__":
    app.run(host=os.environ.get("IP"),
            port=int(os.environ.get("PORT")),
            debug=True)

你知道吗关于.html你知道吗

{% extends 'base.html' %} {% block content %}

<h2>{{ page_title}}</h2>
<p>
    StarCraft is a military science fiction media franchise, created by Chris Metzen and James Phinney and owned by Blizzard Entertainment. The series, set in the beginning of the 26th century, centers on a galactic struggle for dominance among four species—the
    adaptable and mobile Terrans, the ever-evolving insectoid Zerg, the powerfully enigmatic Protoss, and the "god-like" Xel'Naga creator race—in a distant part of the Milky Way galaxy known as the Koprulu Sector. The series debuted with the video game
    StarCraft in 1998. It has grown to include a number of other games as well as eight novelizations, two Amazing Stories articles, a board game, and other licensed merchandise such as collectable statues and toys.
</p>

{% for member in company %}
<div class="row featurette">
    <div class="col-md-7">
        <h3>{{member.name}}</h3>
        <p>
            {{member.description}}
        </p>
    </div>
    <div class="col-md-5">
        <img class="featurette-image img-responsive" src="{{member.image_source}}"alt="Picture of {{ member.name }}"></img>
    </div>
</div>
<hr class="featurette-divider">

 {% endfor %}

{% endblock %}

JSON文件

[
 {
     "name":"Terrans",
     "description":"The Terrans are a fictional future version of humanity in the StarCraft series. The Terrans are the most splintered of the StarCraft species, consisting of multiple factions and nations that not only fight the other races but each other as well. Consideredan adaptive and mobile species 'too stubborn or stupid to know when to give up' when faced with existential threat, the Terrans are noted in the lore of the series for their ability to quickly access and drain a planet's resources. The Terranshave been dedicated a full campaign in each real-time strategy video game installment to date, and are defined in-game by their specialization of units and tactics of defense, tanking, mobility, and overwhelming concentrated firepower; they are the only faction to not field any 'melee unit'. In the series' storyline, the Terrans are usually displayed as being caught in the conflict's crossfire between the Protoss and Zerg; they are forced to fight superior alien powers on two-frontwar at tremendous technological and evolutionary disadvantage, each determined to destroy the other, while also dealing with frequent internal strife, civil wars and revolutions.",
     "image_source":"https://upload.wikimedia.org/wikipedia/en/f/fd/Tychus_Findlay_%28StarCraft%29.png"
 },
 {
     "name":"Zergs",
     "description":"The Zerg Swarm is a species of xenomorphic 'hyper-evolutionary' superorganisms; they are the overriding antagonists of the StarCraft series. Unlike the Protoss and the Terrans, the Zerg are not 'tool-makers', lacking technological inclination; instead, they 'force-evolve' genetic traits by directed mutation in order to match such technology. Operating as a hive mind-linked 'chain of command', the Zerg strive for 'genetic perfection' by assimilating the unique genetic adaptations of 'worthy' species into their own gene pool, creating numerous variations of specialised strains of Zerg gifted with unique adaptations. Despite being notoriously cunning and ruthlessly efficient, the majority of Zerg species have low intelligence; becoming mindless beasts if not connected to a 'hive-cluster' or a 'command entity'. As with the other two primary races, the Zerg are the subject of a full campaign in each of the series' real-time strategy video games. Zerg units are designed to be cost-efficient and fast to produce, encouraging players to overwhelm their opponents with a sheer numerical advantage. Since the release of StarCraft the Zerg have become a video gaming icon, described by PC Gamer UK as 'the best race in strategy history'. The term 'Zerg Rush' or 'zerging' has entered video gaming lexiconto describe sacrificing economic development in favour of using many low-cost fast/weak units to rush and overwhelm an enemy by attrition or sheer numbers. The tactic is infamous; most experienced real-time strategy players are familiar with the tactic in one form or another.",
     "image_source":"https://upload.wikimedia.org/wikipedia/en/b/be/Hydralisk_%28StarCraft%29.png"
 },
 {
     "name":"Protoss",
     "description":" The Protoss are a sapient humanoid species in the StarCraft series, originating from Aiur, a planet on the fringe of the galaxy. They consist of four societies, the conservative Khalai Protoss, the exiled Nerazim, the abandoned Purifiers and the sadisticTal'darim. The Protoss are depicted as a physically strong species with psionic abilities. The Protoss are the most technologically advanced race of the series and have been dedicated a full campaign in each instalment to date.",
     "image_source":"https://upload.wikimedia.org/wikipedia/en/8/8f/Zealot_%28StarCraft%29.png"
 } 
]

我曾经在JSON对象中只有一个项(不是三个)它工作正常,正如我之前提到的,但我几乎可以肯定这不是问题所在。现在,当我运行它来显示时,循环中的所有HTML都不会显示在屏幕上。你知道吗


Tags: andofthetonameinhtmlas
2条回答

将数据作为races而不是company发送到模板。你知道吗

试试看关于.html地址:

{% extends 'base.html' %} {% block content %}

<h2>{{ page_title}}</h2>
<p>
    StarCraft is a military science fiction media franchise, created by Chris Metzen and James Phinney and owned by Blizzard Entertainment. The series, set in the beginning of the 26th century, centers on a galactic struggle for dominance among four species—the
    adaptable and mobile Terrans, the ever-evolving insectoid Zerg, the powerfully enigmatic Protoss, and the "god-like" Xel'Naga creator race—in a distant part of the Milky Way galaxy known as the Koprulu Sector. The series debuted with the video game
    StarCraft in 1998. It has grown to include a number of other games as well as eight novelizations, two Amazing Stories articles, a board game, and other licensed merchandise such as collectable statues and toys.
</p>

{% for member in races %}
<div class="row featurette">
    <div class="col-md-7">
        <h3>{{member.name}}</h3>
        <p>
            {{member.description}}
        </p>
    </div>
    <div class="col-md-5">
        <img class="featurette-image img-responsive" src="{{member.image_source}}"alt="Picture of {{ member.name }}"></img>
    </div>
</div>
<hr class="featurette-divider">

 {% endfor %}

{% endblock %}

相关问题 更多 >

    热门问题