一个Python函数相互抵消

2024-09-27 19:26:16 发布

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

我对Python还比较陌生,实际上我必须投入更多的时间来学习它。现在,我正在使用Python、Jinja2、Flask和SASS创建一个投资组合。一般来说,我现在正在遵循CS50教程,并修改他们的代码以满足我的需要

我不完全理解它们的语法,但我对函数的熟悉加上对文档的阅读帮助我创建了第一个很酷的函数:它占用了我的本地时间,并且取决于它是否适当地向您打招呼(通过jinja2插入html)

我现在想通过数组的jinja2元素创建一个无序列表。以下是my.py的完整代码:

from flask import Flask, render_template, flash, redirect, request, url_for
from datetime import datetime

app = Flask(__name__)

@app.route("/")
def index():
time = datetime.now().time()
if time.hour > (0) and time.hour < (12):
    headline1 = "Good morning,  !"
    return render_template("index.html", headline1=headline1)
elif time.hour >= (12) and time.hour < (18):
    headline2 = "Good afternoon,  !"
    return render_template("index.html", headline2=headline2)
else:
    headline3 = "Good evening,  !"
    return render_template("index.html", headline3=headline3)

def nav():
names = ["Home", "About me", "Projects", "Hobby"]
return render_template("index.html", names=names)

和HTML与Jinja2:

<body>
{% if headline1 %}
<H2>{{ headline1 }}</H2>
{% elif headline2 %}
<H2>{{ headline2 }}</H2>
{% else %}
<H2>{{ headline3 }}</H2>
{% endif %}
<ul>
{% for name in names %}
<li>{{ name }}</li>
{% endfor %}
</ul>
</body>

无论哪个函数是第一个,它都是唯一的工作函数。不管我把哪个作为第二个,它都会被丢弃

抱歉,如果这是一个傻瓜的问题,但我做错了什么?两个函数都是合法的,但似乎存在一个函数抵消另一个函数的问题。我知道我有很多东西要学,但你的回答会对我有很大帮助。提前谢谢


Tags: 函数flaskdatetimeindexreturntimenameshtml
1条回答
网友
1楼 · 发布于 2024-09-27 19:26:16

FWIW:使用所有不同的标题变量是没有意义的,这样就可以了。您的nav函数没有绑定到URL,因此不会调用它

app = Flask(__name__, template_folder='template')
names = ["Home", "About me", "Projects", "Hobby"]

@app.route("/")
def index():
  time = datetime.now().time()
  if time.hour > 0 and time.hour < 12:
    headline = "Good morning,  !"
  elif time.hour >= 12 and time.hour < 18:
    headline = "Good afternoon,  !"
  else:
    headline = "Good evening,  !"
  return render_template("index.html", headline=headline, names=names)

和HTML与Jinja2:

<body>
{% if headline %}
<H2>{{ headline}}</H2>
{% endif %}
<ul>
{% for name in names %}
<li>{{ name }}</li>
{% endfor %}
</ul>
</body>

相关问题 更多 >

    热门问题