Как отображать данные json, используя цикл for с колбой

Я пытался отобразить данные JSON в HTML, используя flask, используя цикл {% for bring in company %} ... {% endfor %}, но безуспешно. Однако я применил JSON к странице about.html, используя прямое приложение с данными/именем, например: {{races[0][name]}}, и это сработало. я не знаю в чем проблема

Я даже пытался найти его и не нашел никакого решения.

Питон/Фласк

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)

about.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-код внутри цикла не отображается на экране, когда я запускаю его для отображения.

Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
0
0
818
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Вы отправляете данные в шаблон как races, а не company.

Так это опечатка, по сути?

roganjosh 28.06.2019 22:49

@roganjosh да. Я поместил цикл for, используя самое старое имя шаблона, так как повторно использовал его из другого кода. Итак, вместо того, чтобы помещать {% for member in races %} в about.html и отображать в python races=data. Я использовал {% for member in company %}. Вот почему проблема.

Elias Prado 28.06.2019 23:21

попробуйте about.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 %}

Другие вопросы по теме