【问题标题】:Django Multiple template inheritanceDjango 多模板继承
【发布时间】:2013-01-09 12:39:51
【问题描述】:

我的情况很简单:

  • 我有一个文本/普通邮件模板: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 部分。

编辑:

类似的东西:

invitation/body.txt

{% extends body.txt invitation.txt %}

invitation/body.html

{% extends body.html invitation.txt %}

【问题讨论】:

  • 另一个想法:{% if html %}{% extends base.html %}{% else %}{% extends base.txt %}{% endif %}

标签: django templates django-templates jinja2


【解决方案1】:

您可以使用include

例如: invitation.txt

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

Your inscription has bee accepted. Welcome!

invitation/body.txt

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

invitation/body.html

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

【讨论】:

    【解决方案2】:

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

    ininvitation.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'}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 2015-11-13
      • 2010-12-23
      • 1970-01-01
      相关资源
      最近更新 更多