如何在模板中呈现django-taggit的公共标签



我看到了很多关于如何使用django-taggit获得最常见标签的问题和答案。然而,这不是我真正的问题。我的问题是如何将这些通用标签传递给我的django模板。

返回所有的标签:

{% for tag in model.tags.all %}
<p>{{tag}}</p>
{% endif %}

效果很好。但是如何返回模板中的公共标记呢?为了获得公共标签,我有这样的:

class Home(ListView):
model = Model
template_name = 'home.html'
def get_common_tags(self):
common_tags = Model.tags.most_common()[:2]
return common_tags

但是我如何访问这些common_tags呢?我需要从模板中获得公共标签还是应该从视图中传递它们?

最好读一下Django GCBV。

在你的例子中:

class Home(ListView):
model = Model
template_name = 'home.html'
...
def get_context_data(self, **kwargs):
kwargs['common_tags'] = self.get_common_tags()
return super().get_context_data(**kwargs)

在这里我们重写get_context_data,以获得模板变量common_tagshttps://docs.djangoproject.com/en/4.0/ref/class-based-views/mixins-single-object/django.views.generic.detail.SingleObjectMixin.get_context_data

之后,在模板中:¶

{% for tag in model.tags.all %}
<p>{{tag}}</p>
{% endif %}
<p> Most common tag are: {{ common_tags }}</p>

common_tags -是一个列表,你可以用django模板过滤器做一些东西,像join:

{{ common_tags|join:" ," }}

unordered_list:

<ul>{{ common_tags|unordered_list }}</ul>

more - here:https://docs.djangoproject.com/en/4.0/ref/templates/builtins/无序列表

最新更新