【问题标题】:One python function canceling out other一个python函数抵消了其他
【发布时间】:2018-12-23 04:29:11
【问题描述】:

我对 Python 还很陌生,实际上我将不得不投入更多时间来学习它。至于现在,我正在使用 Python、Jinja2、Flask 和 SASS 创建一个作品集。一般来说,我目前正在关注 CS50 教程,并正在修改他们的代码以满足我的需要。

我不完全理解它们的语法,但是我对函数的熟悉加上对文档的阅读帮助我创建了第一个很酷的函数:它需要我的本地时间,并且取决于一个小时它会适当地迎接你(通过插入 html jinja2).

我现在想通过数组的 jinja2 元素应用来创建一个无序列表。这是我的 .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)

以及带有 Jinja2 的 HTML:

<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>

无论哪个功能在前,它都是唯一的工作功能。无论我将哪个作为第二个,它都会被丢弃。

对不起,如果这是一个菜鸟的问题,但我做错了什么?这两个功能都是合法的,但似乎存在一个功能抵消另一个功能的问题。我知道我还有很多东西要学,但是您的回答将在此过程中对我有很大帮助。提前致谢!

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    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)
    

    以及带有 Jinja2 的 HTML:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多