문제

저는 Django를 처음 접했고 향후 프로젝트를위한 도구 상자를 구축하려고합니다. 마지막 프로젝트에서 내장형 템플릿 태그가 내가 필요한 것을 수행하지 않았을 때, 나는 템플릿의 엉망진창이 그 기능에서 신발을 신을 것입니다. 나중에 시간과 못생긴 코드를 절약 할 수있는 템플릿 태그를 찾았습니다.

그렇다면 Django에 내장되지 않은 유용한 템플릿 태그는 무엇입니까?

도움이 되었습니까?

해결책

시작하겠습니다.

http://www.djangosnippets.org/snippets/1350/

스마트 { % if %} 템플릿 태그

당신이 진정한 시험보다 더 많은 것이 필요한 것을 발견했다면,이 태그는 당신을위한 것입니다. 그것은 평등,보다 크고, 연산자보다 적은 것을 지원합니다.

간단한 예

{% block list-products %}
    {% if products|length > 12 %}
        <!-- Code for pagination -->
    {% endif %}

    <!-- Code for displaying 12 products on the page -->

{% endblock %}

다른 팁

Smart-IF. 정상을 허용합니다 if x > y 무엇보다도 템플릿에 구성됩니다.

더 나은 if 태그는 이제 Django 1.2의 일부입니다 (참조 릴리스 노트), 릴리스로 예정되어 있습니다 2010 년 3 월 9 일.

James Bennet의 최상의 디아믹스 get_latest 꼬리표

JPartogi의 의견에 대한 응답으로 편집

class GetItemsNode(Node):
    def __init__(self, model, num, by, varname):
        self.num, self.varname = num, varname
        self.model = get_model(*model.split('.'))
        self.by = by

    def render(self, context):
        if hasattr(self.model, 'publicmgr') and not context['user'].is_authenticated():
            context[self.varname] = self.model.publicmgr.all().order_by(self.by)[:self.num]
        else:
            context[self.varname] = self.model._default_manager.all().order_by(self.by)[:self.num]
        return  ''

<div id="news_portlet" class="portlet">
{% get_sorted_items cms.news 5 by -created_on as items %}
{% include 'snippets/dl.html' %}
</div>
<div id="event_portlet" class="portlet">
{% get_sorted_items cms.event 5 by date as items %}
{% include 'snippets/dl.html' %}
</div>

나는 그것을 부른다 get_sorted_items, 그러나 그것은 James의 블로그 포스트를 기반으로합니다

CORE COSE { % Autopaginate Queryset %} (http://code.google.com/p/django-pagination/) 유용합니다. 예를 들어:

#views.py
    obj_list = News.objects.filter(status=News.PUBLISHED)
    # do not use len(obj_list) - it's evaluate QuerySet
    obj_count = obj_list.count()

#news_index.html
    {% load pagination_tags %}
    ...
    # do not use {% if obj_list %}
    {% if obj_count %}
        <div class="news">
        <ul>
        {% autopaginate obj_list 10 %}
        {% for item in obj_list %}
            <li><a href="...">{{ item.title }}</a></li>
        {% endfor %}
        </ul>
        </div>
        {% paginate %}
    {% else %}
        Empty list
    {% endif %}

그 OBJ_List ~ 해야 하다 게으르십시오 - 읽기 http://docs.djangoproject.com/en/dev/ref/models/querysets/#id1

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top