【问题标题】:how to display <head> tags when rendering html template渲染html模板时如何显示<head>标签
【发布时间】:2021-02-26 07:13:13
【问题描述】:

我正在学习如何通过烧瓶渲染 html 模板。问题是下面的 html 文件的头标签永远不会显示。仅显示标签。 请告诉我如何显示标签

python 代码

from flask import Flask, url_for
from flask import request
from flask import render_template

app = Flask(__name__) # Flask(__name__)

@app.route('/')
@app.route('/index')
def index():
user = {'username': 'AWA'}
return render_template('index.html', title='Home', user=user)

@app.route('/layout')
def layout():
return render_template('layout.html')

if __name__ == '__main__':
    app.run(debug = True)

代码

    <html>
    <head>
    {% if title %}
            <title>{{ title }} - Microblog</title>
    {% else %}
        <title>Welcome to Microblog</title>
    {% endif %} 

    </head>
    <body>
        <h1>Hello, {{ user.username }}!</h1>
    </body>
</html>

【问题讨论】:

  • 我认为flask 并不关心占位符在HTML 文件中的位置(头部与主体)。您是否尝试在浏览器上查看页面源以查看占位符是否被删除?您是否尝试过在头部使用更简单的已知工作占位符,例如&lt;title&gt;{{ user.username }}&lt;/title&gt;?或者尝试将{{ title }} 放入正文中以确保它按预期进行转换?

标签: python html python-3.x flask flask-restful


【解决方案1】:

&lt;head&gt; 标记中的数据通常对最终用户不可见。它通常用于元数据、css 文件,有时也用于 js。此外,&lt;title&gt; 标记纯粹是为了让浏览器显示在标题栏中。您可能需要https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header 标签。

您可以在此处阅读有关 head 标签的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head,以及在此处阅读标题标签:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head

编辑:

您可以将&lt;header&gt; 标记与&lt;h1&gt; 结合使用来制作可见的标题,这是一个简单的示例(代码未经测试):

<html>
    <head>
    {% if title %}
            <title>{{ title }} - Microblog</title>
    {% else %}
        <title>Welcome to Microblog</title>
    {% endif %} 

    </head>
    <body>
        <header>
            {% if title %}
                <h1>{{ title }} - Microblog</h1>
            {% else %}
                <h1>Welcome to Microblog</h1>
            {% endif %}
        </header>
        <h3>Hello, {{ user.username }}!</h3>
    </body>
</html>

【讨论】:

  • 能否请您告诉我hpw修改html代码以便显示title标签的代码
  • 据我所知,标题标签无法显示,但您可以使用带有 h1 元素的标题元素(带有标题内容)。 (并将您好,{{user.username}} 更改为 h3)
  • @LetsamrIt 在我的回答中添加了示例代码
猜你喜欢
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 2013-10-29
  • 2017-02-11
相关资源
最近更新 更多