【问题标题】:How can I create a sidebar in all my Django templates using CBV?如何使用 CBV 在我的所有 Django 模板中创建侧边栏?
【发布时间】: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>

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

【问题讨论】:

    标签: python django django-templates django-class-based-views


    【解决方案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 %} 我不知道在这种情况下如何正确渲染它。
    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多