2011-08-11 4 views
0

나는 장고 애플리케이션, 블로그를 가지고있다. 블로그에 대한 항목은/year/month/day/slug URL 패턴을 통해 액세스 할 수 있지만 정상적으로 작동합니다. 내 웹 사이트의 템플릿에 액세스 할 수있는 보관 목록을 만들고 싶습니다. 그래서 가장 좋은 솔루션은 필요한 정보를 만들고 반환하는 templatetag를 만드는 것이라고 생각했습니다. 현재 연도에 대한django templatetags가있는 아카이브 목록

August 2011 
July 2011 
etc.. 
2010 
2009 
2008 
etc.. 

그래서 만 표시 개월 :

나는 아카이브의 형식과 같은 싶었다.

from django.template import Library, Node, TemplateSyntaxError 
from core.blog.models import Entry 
import datetime, calendar 

register = Library() 

class ArchiveNode(Node): 
    def __init__(self, varname): 
     self.varname = varname 

    def render(self, context): 
     temp = list() 

     #Get Info about the first post 
     first = Entry.objects.order_by("pub_date")[0] 
     first_year = first.pub_date.year 
     first_month = first.pub_date.month 

     #Loop over years and months since first post was created 
     today = datetime.datetime.today() 
     this_year = today.year 
     this_month = today.month 

     for year in range(this_year - first_year): 
      if year != this_year: 
       temp += (year,'/blog/'+year+'/') 
      else: 
       for month in range(this_month - first_month): 
        month_name = calendar.month_name[month] 
        temp += (month_name+" "+year,'/blog/'+year+'/'+month+'/') 
     context[self.varname] = temp.reverse() 
     return '' 

@register.tag 
def get_archive(parser, token): 
    bits = token.contents.split() 
    if len(bits) != 3: 
     raise TemplateSyntaxError, "get_archive tag takes exactly 1 argument" 
    if bits[1] != 'as': 
     raise TemplateSyntaxError, "second argument to get_archive tag must be 'as'" 
    return ArchiveNode(bits[2]) 

당신이 메신저 이름과 URL을 포함하는 튜플의리스트를 돌려 볼 수 있듯이 :

이 내가 생각 해낸 태그입니다. 이것이 장고에서 유효할까요? 또는 일부 장고 컨테이너에 정보를 포장해야합니까? (아무 것도 반환하지 않는 것 같습니다)

이것은 ctrl-dev.com/blog에서 작동하는 사이트입니다. 아카이브는 오른쪽 하단의 녹색 상자에 있습니다.

답변

0

특별한 것을 돌려 줄 필요가 없습니다. Django는 파이썬 일 뿐이므로 원하는 것을 반환 할 수 있습니다. 이 경우 나는 (그냥 발명) {{'title':'some title if you want','year': 'year if you want', 'url': url}, {...}, ...} 같은 사전을 반환하는 것이 좋습니다 것입니다. 그런 다음 템플릿을 실행하면 다음과 같이 실행됩니다.

{% for entry in returned_dict %} 
    <a href="{{ entry.url }}">{{ entry.title }}</a> 
{% endfor %} 

또한 링크를 코드에 하드 코드하지 않는 것이 좋습니다. URL 확인자에 대해 https://docs.djangoproject.com/en/dev/topics/http/urls/을 읽은 다음 {% url %} 템플릿 태그에 대해 https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#url을 읽으십시오. 당신은 URL에 이름을 붙일 수 있으며 나중에 코드에서 하드 코딩하지 않고 원하는 내용으로 URL을 가져올 수 있습니다. 이것은 앞으로 도움이 될 것입니다;)

도움이 되길 바랍니다.

+0

답장을 보내 주셔서 감사합니다. :) 링크가 좋은 읽을 거리였습니다. 당신이 제안한 것처럼 끝내고, 제목, 년, 월이있는 딕트를 반환하십시오. 그런 다음 URL을 다음과 같이 검색하십시오. {% url EntryByMonth link.year link.month %} – mXed

+0

도움이된다는 소식을 듣고 기쁘게 생각합니다! –