如何使用 CBV 在我的所有 Django 模板中创建侧边栏?

Posted

技术标签:

【中文标题】如何使用 CBV 在我的所有 Django 模板中创建侧边栏?【英文标题】:How can I create a sidebar in all my Django templates using CBV? 【发布时间】:2015-04-03 22:30:38 【问题描述】:

我的问题是我的所有页面上都需要动态标签列表,并且该页面上的所有帖子(一篇帖子)内容也需要。如何使用基于类的视图在所有页面上包含标签侧边栏?谢谢。

编辑: 标签列表必须按使用频率排序。 我的代码:

class AllTagCloudView(ListView):
    model = Tag
    template_name = 'tag_cloud.html'
    context_object_name = 'tag_cloud'

    def get_queryset(self):
        qs = Tag.objects.values("name", "slug").annotate(Count("post")).order_by('-post__count')
        return qs

我尝试过使用

@register.inclusion_tag('tag_cloud.html', takes_context=True)
def sidebar_sorted_tags(context):

但我不明白如何做到这一点。

我也尝试过使用 % include 'tag_cloud.html' %:

<div>
    <p>Tags</p>
    % for tag in tag_cloud %
        <ul>
            <li><a href="/tag/ tag.get_absolute_url "> tag.name </a></li>
        </ul>
    % empty %
        <a href="">There is no tags yet</a>
    % endfor %
</div>

我认为这很愚蠢,或者我做错了什么。

【问题讨论】:

【参考方案1】:

此任务与基于类的视图无关。您需要使用自定义inclusion template tag。

@register.inclusion_tag('tag_cloud.html')
def sidebar_sorted_tags():
    return 'tag_cloud': Tag.objects.values("name", "slug")
                            .annotate(Count("post")).order_by('-post__count')

现在在你的base.html 模板中写:

% load my_tags %

% sidebar_sorted_tags %

【讨论】:

我尝试使用它,但不明白如何在我的情况下实现它。 查看更新后的答案。 my_tags 是您的标签库的名称。【参考方案2】:

您可以使用context processors 和全局基本模板,您的所有其他模板都将使用extend。您也可以在模板标签中使用简单的include,而不是全局基本模板。

【讨论】:

使用 'include' 渲染 % empty % 我不知道在这种情况下如何正确渲染它。

以上是关于如何使用 CBV 在我的所有 Django 模板中创建侧边栏?的主要内容,如果未能解决你的问题,请参考以下文章

使用 CBV 在 Django 中的一个视图/模板中的两个模型表单

在所有django CBV中自动设置next的值

.items 不适用于 Django 模板中的 defaultdict

使用 Django CBV 模型重定向后的白色 HTML 页面

在django中渲染模板后如何在我的视图中调用一些逻辑

django中cbv源码和restful规范