如何使用从一个基本模板继承的多个模板?蟒蛇,烧瓶

时间:2014-11-17 14:46:32

标签: python html templates flask web-deployment

我有这样的目录结构(来自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.html,但instance.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错误地初始化了我的网页吗?

1 个答案:

答案 0 :(得分:0)

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

@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')