2011-04-21 27 views
3

我想爲匿名用戶使用django片段緩存,但爲已認證的用戶提供新數據。這似乎工作正常:只爲匿名用戶使用django片段緩存

{% if user.is_anonymous %} 

    {% load cache %} 
    {% cache 300 "my-cache-fragment" %} 
     <b>I have to write this out twice</b> 
    {% endcache %} 

{% else %} 

    <b>I have to write this out twice</b> 

{% endif %} 

唯一的問題是,我不得不重複的HTML緩存。除了把它放在包含內容之外,有沒有一些巧妙的解決方法?謝謝。

回答

0

不知道我理解這個問題......

{% load cache %} 
{% cache 300 "my-cache-fragment" %} 
    <b>I have to write this out twice</b> 
{% endcache %} 

{% if not user.is_anonymous %} 
    <b>And this is the extra uncached stuff for authenticated users</b> 
{% endif %} 
+0

這對於匿名用戶和經過身份驗證的用戶來說都是一樣的。唯一的區別是一個在緩存標籤內,一個在外面。 – asciitaxi 2011-04-21 06:24:46

+0

儘管這是一種有效的方法,但它可能會在不同的情況下破裂: 有一個'{%block something%} {%endblock%}'會產生一個錯誤(不允許多次使用同一個blocktag) – Hussam 2013-01-04 12:12:47

2

嘗試認證用戶緩存超時設置爲零。

views.py:

context = { 
    "cache_timeout": 300 if request.user.is_anonymous() else 0, 
} 

模板:

{% load cache %} 
{% cache cache_timeout "my-cache-fragment" %} 
    <b>I have to write this only once</b> 
{% endcache %} 
+0

這是[類似的答案](http://stackoverflow.com/a/24519003/64911),將所有邏輯放在模板中(好或壞)。 – mlissner 2015-12-11 22:34:39

0

你可以傳遞參數獲取到cache標籤就像指定緩存:

{% cache 500 sidebar request.user.is_anonymous %} 

檢查here獲取更多信息。 .. 但是,這也將緩存數據爲登錄用戶也...

也許你得寫一個custom template tag。您可以先檢查現有的cache標籤並根據該代碼創建自定義標籤。但是不要忘記,Django緩存非常強大和複雜(比如在模板緩存中支持不同的語言)。

1
{% with cache_timeout=user.is_staff|yesno:"0,300" %} 
    {% cache cache_timeout cacheidentifier user.is_staff %} 
      your content here 
    {% endcache %} 
{% endwith %}