在Flas中呈现(许多)模板

2024-09-20 04:00:33 发布

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

我想有一个主页,在选项a和选项B之间进行选择。当我单击其中一个选项时,我想转到page1.html(选项a)或page2.html(选项B)。你知道吗

我有这些文件:

static/
  route.js
templates/
  index.html
  page1.html
  page2.html
web_server.py
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/opta')
def optionA():
    return render_template('page1.html')

@app.route('/optb')
def optionB():
    return render_template('page2.html')

index.html

<body>
    <button id="optionA">Option A</button>
    <button id="optionB">Option B</button>
    <script src="{{url_for('static', filename='route.js')}}"></script>
</body>

route.js

$("#optionA").click(function(e) {
    $.ajax({
        type: "GET",
        url: "/opta",
        contentType: 'application/json;charset=UTF-8',
        success: function(result){
            console.log("Hooray");
            window.location.replace("{{ url_for('optA') }}"); // doesn\'t work
            var divA = $("#a"); divA.html(result); // (a is a div in page1.html) doesn\'t work too
        },
        error: function(textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
});

// same for option B

Tags: appurlindexreturndefhtml选项js
3条回答

当然了:

<script src="{{url_for('static', filename='route.js')}}"></script>

将从“静态”资源中获取您的javascript文件-这意味着它是按原样提供的,而不是解释为模板。flask中使用的Jinja2模板机制可以在Javascript文件中使用,但是您必须通过一个视图来提供它,就像您处理“index”和“opt*”url一样(然后,应该将.js文件放在适当的templates dir中,而不是放在“static”中)。你知道吗

不要将Javascript作为模板来使用(这通常比不这样做更危险,也会使维护Javascript代码更困难),您可以只在主index模板中放入一个简单的Javascript片段,只需设置文档的url变量。然后,获取的javascript将使用主html文档中的内联变量集。你知道吗

为了给出更准确的答案,我们可能需要更多关于要显示的页面的描述。 如果页面完全不相关,您可以去掉javascript,然后使用以下html代码:

<body>
    <a href="/opta"> <button id="optionA">Option A</button> </a>
    <a href="/optb"> <button id="optionB">Option B</button> </a>
</body>

如果在flask中呈现多个模板的意思是使用索引.html在页面“A”和“B”中布局,然后我会阅读jinja2文档中的child template部分

首先,根据您概述的内容,您基本上只需要一个具有不同选项的路由,因此在Flask上,您可以使用Flaskvariable rules处理一个路由:

@app.route('/', defaults={'page':None})
@app.route('/<page>')
def index(page):
    if page == None: 
        return render_template('index.html')
    else:
        return render_template(page)

在html模板上,正如几个注释所提到的,您只需要<a>标记,而不需要按钮和javascript:

<body>
    <a href="page1.html" id="optionA">Option A</a>
    <a href="page2.html" id="optionB">Option B</a>
</body>

相关问题 更多 >