2016-07-02 86 views
0

我創建Django的HTML電子郵件模板,看起來是這樣的:飼養HTML DRY

<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代碼中,但我想不出更好的方法? 任何想法或更好的方法來實現這一點?

回答

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

main.html中

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

正如你所不包括的電子郵件模板內部或外部CSS文件,可以考慮使用此library

+1

我的理解是我不能將css文件添加到電子郵件模板,它必須是內聯樣式。或者這是不正確的? – Johan

+1

你說得對。看看這個https://github.com/roverdotcom/django-inlinecss – navit

+0

非常好,謝謝! – Johan