Django多模板继承

Nat*_*tim 4 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 }}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

当然,翻译,css和多个块有点复杂.

我的愿望是定义invitation.txt:

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

Your inscription has bee accepted. Welcome!
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

像这样的东西:

邀请/ body.txt:

{% extends body.txt invitation.txt %}
Run Code Online (Sandbox Code Playgroud)

邀请/ body.html:

{% extends body.html invitation.txt %}
Run Code Online (Sandbox Code Playgroud)

fur*_*ins 7

你可以使用include

例如: invitation.txt:

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

Your inscription has bee accepted. Welcome!
Run Code Online (Sandbox Code Playgroud)

邀请/ body.txt:

{% extends body.txt %}
{% block message %}
{% include "invitation.txt" %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

邀请/ body.html:

{% extends body.html %}
{% block message %}
{% include "invitation.txt" %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)


小智 6

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

在invitation.txt中:

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

Your inscription has been accepted. Welcome!
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

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