[英]A-z Index Django
Im looking for advice on desinging a web page with an A - Z index. 我正在寻找有关设计具有A-Z索引的网页的建议。
Kind of like : 有一些像 :
http://www.bls.gov/bls/topicsaz.htm I have a long list of objects, with a title, that I want do display alphabetically, easy! http://www.bls.gov/bls/topicsaz.htm我有一长串带有标题的对象,我想按字母顺序显示它们,很容易!
But I want to put in the AZ with anchors, do I do this in the template, 但是我想使用锚点放入AZ,是否在模板中这样做,
I would have to loop through all the objects in the template, storing the currentletter as a global. 我将不得不遍历模板中的所有对象,将currentletter存储为全局对象。 Then check if each objects starts with the current letter etc etc.
然后检查每个对象是否以当前字母等开头。
It's not nice, is there any easier way that I am missing. 这不是很好,有什么更简单的方法让我错过了。
Maybe I should do it in the python code? 也许我应该在python代码中这样做?
You may use reqroup template tag to group item... Let headline be your field to be indexed... First, in your view filter your objects and add an index parameter to each for grouping: 您可以使用reqroup模板标签对项目进行分组...让标题成为要索引的字段...首先,在视图中过滤对象并为每个对象添加索引参数以进行分组:
objectList = SomeModel.objects.all()
for x in objectList:
x.__setattr__('index', x.headline[0])// first letter of headline
Regroup Documentation , have enough information for the rest, but simply, regrup by index and anchor item.grouper as index link... 重新整理文档 ,具有足够的其余信息,但是简单地,按索引和锚item.grouper作为索引链接进行重复...
Looking through the django template tags I found a nice way of doing it {{ifchanged}} , its worth mentioning for future use. 通过查看django模板标签,我发现了一种不错的{{ifchanged}}方法 ,值得一提,以备将来使用。
My list of objects is passed to my template ordered alphabetically: 我的对象列表按字母顺序传递到我的模板:
Objects.get.all().order_by('title')
Then in my template i do : 然后在我的模板中,我做:
# loop through all objects
{% for obj in objs %}
#display the letter only when it changes
{% ifchanged obj.title.0 %}<h1>{{obj.title.0}}</h1>{% endifchanged%}
# display the object
<h2>obj.title</h2>
{% endfor %}
Its a very handy 1 line peice of code in the template. 它是模板中非常方便的1行代码。
There are a couple snippets that might help you: 有一些摘要可以帮助您:
http://djangosnippets.org/snippets/1364/ http://djangosnippets.org/snippets/1364/
http://djangosnippets.org/snippets/1051/ http://djangosnippets.org/snippets/1051/
The Washington Times had a nice blog post about building an alphabetical filter for the admin which might give you some helpful ideas. 《华盛顿时报》(Washington Times)上有一篇不错的博客文章,内容涉及为管理员构建字母过滤器,这可能会给您一些有用的想法。
You can also just use regroup directly in the template: 您也可以直接在模板中直接使用regroup:
{% regroup object_list by name.0 as letters %}
{% for letter in letters %}
<div class="letter_group" id="index_{{letter.grouper}}">
<h2>{{letter.grouper}}</h2>
<ul>
{% for object in letter.list %}
<li><a href="{% url object_show object.pk %}">{{object}}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.