简体   繁体   English

如何不在Django中仅缓存我的模板的一段代码

[英]How not to cache only a piece of code of my template in django

Under django v. 1.4. 根据django v.1.4。

The problem: 问题:

Since my template is rendered by this view which will be totally stored in cache: 由于我的模板是通过此视图呈现的,因此将完全存储在缓存中:

@cache_page(60*60*24)
def index(request):
    foo_form = FooForm()
    context = RequestContext(request, {
        'foo_form': foo_form
    })
    # An entire page is rendered
    return render_to_response('index.html', context_instance=context)

In my template I have an if statement which checks whether user is authenticate: 在我的模板中,有一个if语句,用于检查用户是否通过身份验证:

...
<li>
    {%  if user.is_authenticated %}
        <a href="{% url 'home' %}" class="login">Enter</a>
    {% else %}
        <a href="" class="login" data-target="#login_modal" data-tggle="modal">Enter</a>
    {% endif %}

</li>
...

There is a modal that's activated by a button "Enter" which should be displayed when there's no user logged, otherwise the user is redirected to the system when the "Enter" button is clicked. 有一个由“ Enter”按钮激活的模式,当没有用户登录时,应显示该模式,否则,当单击“ Enter”按钮时,用户将被重定向到系统。

The question: Is there a way to ignore only that piece of code from my template to be not cached? 问题:是否可以忽略模板中的那部分代码而不进行缓存? If so, how? 如果是这样,怎么办?

You should use Template fragment caching: https://docs.djangoproject.com/en/1.6/topics/cache/#template-fragment-caching 您应该使用模板片段缓存: https : //docs.djangoproject.com/en/1.6/topics/cache/#template-fragment-caching

{% load cache %}
{% cache 500 sidebar request.user.username %}
    .. sidebar for logged in user ..
{% endcache %}

Use ajax to display the user authentication template, so caching wont affect your template. 使用ajax显示用户身份验证模板,因此缓存不会影响您的模板。

<li>

`{%  if user.is_authenticated %}`
   ` <a href="{% url 'home' %}" class="login">Enter</a>`
`{% else %}`
    `<a href="" class="login" data-target="#login_modal" data-tggle="modal">Enter</a>`

{% endif %}

</li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM