【问题标题】:Keeping HTML in Django email templates DRY使 Django 电子邮件模板中的 HTML 保持干燥
【发布时间】:2016-11-04 15:34:36
【问题描述】:

我创建了 Django html 电子邮件模板,看起来像这样:

<p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.6em; font-weight: normal; margin: 10px 0 10px; padding: 0;">
        Hello John
    </p>

<p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.6em; font-weight: normal; margin: 10px 0 10px; padding: 0;">
        Welcome to the site
    </p>

<p style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.6em; font-weight: normal; margin: 10px 0 10px; padding: 0;">
        More text here...
    </p>

因为它是一个电子邮件模板,我必须使用内联样式,结果它看起来很丑,我不得不重复自己。我正在寻找一种改进方法。

我的想法是创建一个返回样式信息的模板标签:

@register.filter
def style(tag):
    tags = {
        'p': "style="font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.6em; font-weight: normal; margin: 10px 0 10px; padding: 0;""
# Will add more options here
        }
    return tags[tag]

然后在我的模板中我将使用:

<p|style>
        Hello John
    </p>

<p|style>
        Welcome to the site
    </p>

<p|style>
        More text here...
    </p>

我知道把html放在python代码中并不理想,但我想不出更好的方法? 有什么想法或更好的方法来实现这一目标?

【问题讨论】:

    标签: html django


    【解决方案1】:

    考虑定义一个 CSS 类并将该类分配给所有需要格式化的元素。

    template.css

     .MyEmailStyle {
        font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;
        font-size: 14px; 
        line-height: 1.6em; 
        font-weight: normal; 
        margin: 10px 0 10px; 
        padding: 0;
     }
    

    ma​​in.html

    <p class="MyEmailStyle">
        Hello John
    </p>
    

    由于您不能在电子邮件模板中包含外部或内部 CSS 文件,请考虑使用此library

    【讨论】:

    • 我理解的方式是我不能将 css 文件添加到电子邮件模板中,它必须是内联样式。或者这是不正确的?
    • @Johan: 还有pypi.python.org/pypi/django-premailer 作为django-inlinecss 的替代品,没有使用过后者,我无法比较它们,但我从来没有抱怨过关于premailerpremailer 提供了使 URL 成为绝对值的附加功能
    • 我都试过了,django-premailer 不支持外部 CSS。和 django-inlinecss 从其依赖项 pynliner 中抛出异常 No match was found. We're done or something is broken。不幸的是,两者都不适合我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2023-03-08
    • 2011-01-04
    • 1970-01-01
    • 2011-08-18
    • 2010-12-16
    相关资源
    最近更新 更多