【问题标题】:How to use multiple templates that inherits from one base template? python, Flask如何使用从一个基本模板继承的多个模板?蟒蛇,烧瓶
【发布时间】:2015-01-14 12:22:12
【问题描述】:

我的目录结构是这样的(来自https://github.com/alvations/APE):

APE
    \app
        \templates
            base.html
            index.html
            instance.html
        __init__.py
        hamlet.py
    config.py
    run.py

我的hamlet.py 应用程序,用这些函数初始化了2个页面:

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
@app.route('/instance')

def index():
    return render_template('index.html')

def instance():
    return render_template('instance.html')

instance.htmlindex.html 都继承自base.html 具有不同的块内容,base.html 看起来像这样:

<!DOCTYPE html>
<html lang="en">

    <head>
        <title>Post Editor Z</title>
    </head>

    <body>

        <div class="container">
            {% block content %}{% endblock %}
        </div><!-- /.container -->

    </body>
</html>

我的 index.html 看起来像这样:

{% extends "base.html" %}
{% block content %}    
 <div class="row">
    <div class="col-lg-12">
      Hello World
    </div>
 </div>
{% endblock %}

我的 instance.html 看起来像这样:

{% extends "base.html" %}
{% block content %}    
 <div class="row">
    <div class="col-lg-12">
      Some instance.
    </div>
 </div>
{% endblock %}

部署后转到http://127.0.0.1:5000/indexhttp://127.0.0.1:5000/instance。他们都给出了index.html的内容

是不是因为base.html只能被另一个html继承?就我而言,我同时拥有从 base.html 继承的 instanceindex html。

我尝试制作base.html 的副本并将其命名为abase.html 并使instance.html 继承自abase.htmlinstance.html 仍然输出Hello World 而不是Some instance.,即我做了这个更改instance.html:

{% extends "abase.html" %}
{% block content %}    
 <div class="row">
    <div class="col-lg-12">
      Hello World
    </div>
 </div>
{% endblock %}

如何解决问题,使 instance.html 和 index.html 显示模板中定义的两个不同页面?

是不是因为我在hamlet.py中错误地初始化了我的页面?

【问题讨论】:

    标签: python html templates flask web-deployment


    【解决方案1】:

    我找到了问题的解决方法,但我不知道它为什么有效。

    @app.route('/instance') 移到instance() 工作之前:

    from flask import render_template
    from app import app
    
    @app.route('/')
    
    @app.route('/index')
    def index():
        return render_template('index.html')
    
    @app.route('/instance')
    def instance():
        return render_template('instance.html')
    

    【讨论】:

    • 之所以有效,是因为@app.route 是函数的装饰器。像以前一样写,每个 url 都指向索引函数。这样你就有了/instance 对应instance() 和其他index()
    • 如果@app.route('/') 没有装饰,下一个函数是@app.route('index')。默认页面将指向index()?
    • @app.route('/') 在此示例中与@app.route('/index') 一起装饰index。现在你的默认页面是index()
    猜你喜欢
    • 2011-04-24
    • 1970-01-01
    • 2016-01-21
    • 2019-09-08
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    相关资源
    最近更新 更多