2017-05-26 54 views
0

可以在django模板中內聯一個摺疊/關鍵的css文件嗎?django模板中的內聯CSS文件

我想的是一樣的東西:

<style>{% inline "css/home.above.css" %}</style>

這將導致:

<style>html {...} body {...} {content of the css file}</style>

但我還沒有發現任何ressources在這方面。

+1

關於[此問題](https://stackoverflow.com/questions/33607083/django-template-embed-css-from-file)的答案說你可以使用'{%include%}'標記。雖然我沒有嘗試過。我能想到的另一種方式是,您可以在視圖中讀取/打開css文件並將其放入模板上下文中。 – xyres

回答

1

爲了擴展我的評論,這是如何將您的CSS文件傳遞到您的模板上下文。

def my_view(request): 
    with open('../path/to/style.css') as infile: 
     css = infile.read() 
     # if you want to remove newlines, uncomment the next line 
     # css = css.replace('\n', '') 
     # if you want to remove tabs, uncomment the next line 
     # css = css.replace('\t, '') 

    return render(request, 'template.html', {'css': css}) 

然後,在你的模板,你可以使用{{ css }}訪問整個CSS文件。


注:不用手動從CSS除去換行和標籤,我認爲這是最好使用CSS壓縮機。例如,如果您使用4個空格而不是製表符,那麼這些額外空間將不會被剝離。

這個庫看起來不錯 - csscompressor

+0

謝謝。我會盡量與django壓縮機聯繫。 – maiis