Django多模板继承

时间:2013-01-25 14:21:40

标签: django templates django-templates jinja2

我的情况很简单:

  • 我有一个text / plain邮件模板:body.txt
  • 另一个用于text / html邮件:body.html

这两封邮件的内容是相同的,因为我使用EmailAlternative在同一邮件中发送。

body.txt

{% block message %}{% endblock %}

{{ site_name }} team
-----------------
If you need help contact use at {{ support_mail }}

body.html

<html>
    <head>
        <title>{% block title %}{% endblock %}</title>
    </head>
    <body>
        <p>{% filter linebreaksbr %}{% block message %}{% endblock %}{% endfilter %}</p>
        <p><strong>{{ site_name }} team</strong></p>
        <hr/>
        If you need help contact use at <a href="mailto:{{ support_mail }}">{{ support_mail }}</a>
    </body>
</html>

当然,翻译,css和多个块都会有点复杂。

我希望定义 invitation.txt

{% block message %}Dear {{ first_name|title }} {{ last_name|upper }},

Your inscription has bee accepted. Welcome!
{% endblock %}

我希望能够加载(body.txt,invitation.txt)以及(body.html,invitation.txt)来获取我的两个html部分。

编辑:

类似的东西:

邀请/ body.txt

{% extends body.txt invitation.txt %}

邀请/ body.html

{% extends body.html invitation.txt %}

2 个答案:

答案 0 :(得分:7)

您可以使用include

例如为: 的 invitation.txt

Dear {{ first_name|title }} {{ last_name|upper }},

Your inscription has bee accepted. Welcome!

<强>邀请/ body.txt

{% extends body.txt %}
{% block message %}
{% include "invitation.txt" %}
{% endblock %}

<强>邀请/ body.html

{% extends body.html %}
{% block message %}
{% include "invitation.txt" %}
{% endblock %}

答案 1 :(得分:5)

您可以在上下文中设置变量并将其传递给extends模板标记。

在invitation.txt中:

{% extends base %}
{% block message %}Dear {{ first_name|title }} {{ last_name|upper }},

Your inscription has been accepted. Welcome!
{% endblock %}

使用上下文{'base': 'body.txt'}呈现invitation.txt,然后使用上下文{'base': 'body.html'}呈现。