擅长:python、mysql、java
<p><a href="https://stackoverflow.com/a/4693498/254553">@Dominique</a>的答案是正确的,但是当你在<code>context_processors</code>中写东西的时候,这会在网站的任何页面加载。这可能会造成性能问题。在</p>
<p>我认为处理动态侧边栏的正确方法是<code>simpletag</code>,并在需要的地方使用。在</p>
<pre><code>def get_sidebar():
tags = Tags.objects.filter(active=True)
latest_posts = Post.objects.all().order_by('-create_at')[:10]
html = render_to_string("sidebar.html", {
"tags": tags,
"latest_posts": latest_posts
})
return html
</code></pre>
<p>现在只需在模板文件中使用:</p>
^{pr2}$
<p>另外,您可以将<code>request</code>传递给<code>simpletag</code>,以使用<code>user.is_authenticated</code>进行经过身份验证的用户访问。在</p>