在Flask中一次渲染多个模板 [英] Render multiple templates at once in Flask

查看:103
本文介绍了在Flask中一次渲染多个模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作Flask应用程序.我有一个登录区域,一个博客区域.如果要获取用户的登录名,我将呈现登录模板.但这不会呈现必须显示在登录区域下方的博客模板.:/

I'm making a Flask application. I have a login area, a blogs area. If I want to get user's login, I'll render login template. But this doesn't render the blog template that has to be displayed below the login area. :/

我会尝试使其更清晰:

{% block login %} {% endblock %}
blah blah
{% block blog_display %} {% endblock %}

现在我有一个 login.html ,它对此进行了扩展,并进入了登录块.我有一个 blogs.html ,它进入了 blog_display .如何同时渲染两者?当我执行 render_template()时,只能在 login.html blogs.html 之一上调用它.

Now i have a login.html which extends this, and goes into login block. I have a blogs.html which goes into blog_display. How to I render both? When I do render_template(), i can call it on only one of the login.html or blogs.html.

请帮帮我.如果您需要,我会提供更多详细信息.

Please help me out. I'll give more details if you ask for it.

推荐答案

您可能会以错误的方式考虑布局.布局是模板的 most 通用模板,而不是最复杂的模板.如果您需要很少的独立功能,则可以按原样编写它们,并按 <在需要的地方添加代码>包含 .

You may be thinking about layouts the wrong way. Your layout is the most generic of your templates, not your most complex one. If you need little self-contained pieces of functionality then write them up just as they are and include them where they are needed.

也就是说,如果您想要这样的东西:

That is to say, if you want something like this:

----------------------------------
                  +--------------+
  Header          |   Login      |
                  +--------------+
----------------------------------

  Body Content (Blog)

您还希望拥有一个独立的登录页面,如下所示:

And you also want to have a stand-alone login page like this:

----------------------------------

  Header

----------------------------------

  +--------------+
  |   Login      |
  +--------------+

然后创建部分登录名,并在需要的地方 include .

Then create a login partial and include it where you need it.

templates/partials/login.html

<form action="/login" method="post">
<!-- Your login goes here -->
</form>

templates/your_base.html

<!DOCTYPE html>
<html>
<head>
{% block head %}
{# 
Default HEAD content goes here 
with extra nested blocks for children to override 
if needed. 
#}
{% endblock head %}
</head>
<body>
<header>{% block header %}{% endblock header %}</header>
{# Note: This assumes we *always* want a header #}
{% block content %}{% endblock content %}
</body>
</html>

templates/login.html

{% extends "your_base.html" -%}
{% block content -%}
{% include "partials/login.html" %}
{%- endblock content %}

templates/blog.html

{% extends "your_base.html" -%}
{% block header -%}
{{ super() }}{# Render the default header contents here #}
{% include "partials/login.html" %}
{%- endblock header %}
{% block content -%}
{# Render your blog posts here #}
{%- endblock content %}

这篇关于在Flask中一次渲染多个模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆