Johan Johan - 5 months ago 9
HTML Question

Keeping HTML in Django email templates DRY

I have created Django html email templates that looks something like this:

<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>


Since it's an email template, I must use inline styles and as a result it looks ugly and I have to repeat myself. I'm looking for a way to improve this.

My idea is to create a template tag that will return the style info:

@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]


Then in my template I will use:

<p|style>
Hello John
</p>

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

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


I know it is not ideal to put html in python code, but I can't think of a better way?
Any thoughts or better ways to achieve this?

Answer

Consider defining a CSS class and assigning this class to all the elements that need to be formatted.

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;
 }

main.html

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

As you can't include external or internal CSS files in an email template, consider using this library.