首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CS50中的Jinja格式

CS50中的Jinja格式
EN

Stack Overflow用户
提问于 2022-09-15 21:50:44
回答 1查看 44关注 0票数 0

我的jinja for循环的格式有问题。它是一个名生成器,它生成一个名和名。我在代码中组合了名字和姓氏,但是当它输出到HTML文件时,它没有格式化,并且有括号。我不知道该在哪里修改它,这可能是我错过的一些简单的东西。你的帮助将不胜感激。谢谢!

Python代码

代码语言:javascript
复制
from cs50 import SQL
from flask import Flask, render_template, render_template_string, request
from tempfile import mkdtemp
import random

# Configure application
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///names.db")



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

@app.route("/results", methods=["POST"])
def results():
    gender = request.form.get("gender")
    number_results = int(request.form.get("number_results"))

    results = []

    for i in range(number_results):
        if gender == "male":
            random_id_male = random.randint(1, 1000)
            random_id_last = random.randint(1, 1000)
            male_name = db.execute("SELECT name FROM male_names WHERE id = ?", random_id_male)
            last_name = db.execute("SELECT name FROM last_names WHERE id = ?", random_id_last)
            total_male = male_name + last_name
            results.append(total_male)
        elif gender == "female":
            random_id_female = random.randint(1, 1000)
            random_id_last = random.randint(1, 1000)
            female_name = db.execute("SELECT name FROM female_names WHERE id = ?", random_id_female)
            last_name = db.execute("SELECT name FROM last_names WHERE id = ?", random_id_last)
            total_female = female_name + last_name
            results.append(total_female)
        elif gender == "other":
            random_id_other = random.randint(1, 300)
            random_id_last = random.randint(1, 1000)
            other_name = db.execute("SELECT name FROM other_names WHERE id = ?", random_id_other)
            last_name = db.execute("SELECT name FROM last_names WHERE id = ?", random_id_last)
            total_other = other_name + last_name
            results.append(total_other)

    return render_template("index.html", results=results)

HTML索引

代码语言:javascript
复制
<head>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, width=device-width">

  <!-- http://getbootstrap.com/docs/5.1/ -->
  <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" rel="stylesheet">
  <script crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"></script>

  <link href="/static/styles.css" rel="stylesheet">

  <title>Fantasy Name Generator</title>

</head>
<header>
  <!-- Background image -->
  <div class="p-5 text-center bg-image" style="background-image: url('https://images.pexels.com/photos/326055/pexels-photo-326055.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'); height: 400px;">
    <div class="mask" style="background-color: rgba(0, 0, 0, 0.6);">
      <div class="d-flex justify-content-center align-items-center h-100">
        <div class="text-white">
          <h1 class="mb-3">Fantasy Name Generator</h1>
        </div>
      </div>
    </div>
  </div>
  <!-- Background image -->
</header>
<body>
  <!--Form to get data from user-->
  <form action="/results" method="post">
      <!--radio buttons to choose gender-->
      <div class="form-check form-check-inline">
        <input class="form-check-input" type="radio" name="gender" id="inlineRadio1" value="male">
        <label class="form-check-label" for="inlineRadio1">Male</label>
      </div>
      <div class="form-check form-check-inline">
        <input class="form-check-input" type="radio" name="gender" id="inlineRadio2" value="female">
        <label class="form-check-label" for="inlineRadio2">Female</label>
      </div>
      <div class="form-check form-check-inline">
        <input class="form-check-input" type="radio" name="gender" id="inlineRadio3" value="other">
        <label class="form-check-label" for="inlineRadio3">Neutral</label>
      </div>
      <div class="flex flex-col items-center">
        <label class="pb-1" for="number_results">results</label>
        <select name="number_results" id="number_results" required class="mb-4 rounded-md">
            <option value="10" selected>10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option value="40">40</option>
            <option value="50">50</option>
        </select>
    </div>
    <button class="btn btn-primary" type="submit">Generate Names</button>
  </form>
      <!-- Names get generated here -->
      <div id="results" class="transition flex flex-col pt-6 md:pt-8" >
        <ul aria-label="results" class="m-auto text-center font-medium tracking-wide column-count-1 sm:column-count-3 lg:column-count-5">
        {% for result in results %}
            <ul class="">{{ result }}</ul>
        {% endfor %}
        </ul>
      </div>
  </body>

输出在index.html页面上的样子

代码语言:javascript
复制
[{'name': 'Oswaldo'}, {'name': 'Navarro'}]
[{'name': 'Jamir'}, {'name': 'Wagner'}]
[{'name': 'Rodrigo'}, {'name': 'Valenzuela'}]
[{'name': 'Davion'}, {'name': 'Molina'}]
[{'name': 'Zechariah'}, {'name': 'Austin'}]
[{'name': 'Jace'}, {'name': 'Conner'}]
[{'name': 'Valentino'}, {'name': 'Zavala'}]
[{'name': 'Kadin'}, {'name': 'Leblanc'}]
[{'name': 'Emmanuel'}, {'name': 'Mccann'}]
[{'name': 'Alexander'}, {'name': 'Erickson'}]
EN

回答 1

Stack Overflow用户

发布于 2022-09-17 22:51:41

cs50 execute方法返回字典列表。list + list (在total_other = other_name + last_name中)返回一个列表,其中包含两个列表中的所有元素。append正在追加一个列表。因此,results是一个列表列表,每个列表包含两个字典。解决这一问题的一种方法是将total_{genders}转换为字符串,而不是字典列表,然后追加到results

每个execute90都返回一个包含一个字典元素的列表,每个字典都有一个键('name'),因此数据将被寻址为row[0]['name']。然后为每个(2部分)名称构建一个字符串并附加到结果列表中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73737787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档