我想製作我的博客上的,顯示了當年側的列表中,並且只有條目的幾個月裏,像這樣的:Django的 - 非連續兩個月
2011 - Jan, Feb
2010 - Jan, Mar, May, Jun, Jul, Aug, Oct, Nov, Dec
2009 - Sep, Oct, Nov, Dec
我已自定義模板標籤這樣我就可以將它放到base.html中。
目前,它產生的,看起來像這樣的列表:
2011 - 1, 2
2010 - 1, 3, 5, 6, 7, 8, 10, 11, 12
2009 - 9, 10, 11, 12
我建立了一個自定義模板標籤是(感謝Alasdair和cig212):
from django import template
from blog.models import Post
register = template.Library()
class PostList(template.Node):
def __init__(self, var_name):
self.var_name = var_name
def render(self, context):
my_months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
arch = Post.objects.dates('publish', 'month', order='DESC')
archives = {}
for i in arch:
year = i.year
month = i.month
if year not in archives:
archives[year] = []
archives[year].append(month)
else:
if month not in archives[year]:
archives[year].append(month)
context[self.var_name] = archives.items()
return ''
@register.tag
def get_post_list(parser, token):
"""
Generates a list of months that blog posts exist.
Much like the 'year' archive.
Syntax::
{% get_post_list as [var_name] %}
Example usage::
{% get_post_list as posts_list %}
(This 'var_name' is the one inserted into the Node)
"""
try:
tag_name, arg = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError, "%s tag requires arguments" % token.contents.split()[0]
m = re.search(r'as (\w+)', arg)
if not m:
raise template.TemplateSyntaxError, "%s tag had invalid arguments" % tag_name
var_name = m.groups()[0]
return PostListNode(var_name)
的模板看起來像這樣:
{% load blog %}
{% get_post_list as posts_list %}
{% for years, months in posts_list %}
{{ years }}
{% for month in months %}
<a href="{{ years }}/{{ month }}">{{ month }}</a>
{% endfor %}
<br />
{% endfor %}
那麼我怎樣才能得到我的my_months
標籤位於由標籤生成的月份數字上的自定義標籤中。我知道我需要在自定義標籤中使用enumerate()
,但我在某個地方迷路了。
那麼你的問題是什麼? – 2011-02-10 21:53:18