如何在 Django 模板中实现面包屑? [英] How to implement breadcrumbs in a Django template?

查看:25
本文介绍了如何在 Django 模板中实现面包屑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Google 上搜索Django 面包屑"时提供的一些解决方案包括使用模板和 block.super,基本上只是扩展基本块并将当前页面添加到其中.http://www.martin-geber.com/思想/2007/10/25/breadcrumbs-django-templates/

Some solutions provided on doing a Google search for "Django breadcrumbs" include using templates and block.super, basically just extending the base blocks and adding the current page to it. http://www.martin-geber.com/thought/2007/10/25/breadcrumbs-django-templates/

http://www.djangosnippets.org/snippets/1289/ - 提供了一个模板标签,但如果您没有正确声明 urls.py,我不确定这是否有效.

http://www.djangosnippets.org/snippets/1289/ - provides a template tag but I'm not sure this would work if you don't have your urls.py properly declared.

我想知道最好的方法是什么?如果您之前已经实施过面包屑导航,您是如何做到的?

I'm wondering what's the best way? And if you have implemented breadcrumbs before how did you do it?

--- 编辑 --

我的问题是:在 Django 中是否有一种普遍接受的方法来做面包屑,但从我看到的答案来看并没有,而且有许多不同的解决方案,我不确定谁来奖励正确的答案到,因为我使用了使用 block.super 方法的变体,而以下所有答案都适用.

My question was meant to be: is there a general accepted method of doing breadcrumbs in Django, but from the answers I see there is not, and there are many different solutions, I'm not sure who to award the correct answer to, as I used a variation of using the block.super method, while all the below answers would work.

我想这是一个过于主观的问题.

I guess then this is too much of a subjective question.

推荐答案

注意:我在下面提供了完整的片段,因为 djangosnippets 最近很挑剔.

酷,居然有人发现了我的片段:-) 我的模板标签的使用是比较简单.

Cool, someone actually found my snippet :-) The use of my template tag is rather simple.

为了回答您的问题,没有处理面包屑的内置"django 机制,但它确实为我们提供了下一个最好的东西:自定义模板标签.

To answer your question there is no "built-in" django mechanism for dealing with breadcrumbs, but it does provide us with the next best thing: custom template tags.

想象一下你想要这样的面包屑:

Imagine you want to have breadcrumbs like so:

Services -> Programming
Services -> Consulting

那么你可能会有几个命名的 url:services"、programming"、consulting":

Then you will probably have a few named urls: "services", and "programming", "consulting":

    (r'^services/$',
     'core.views.services',
     {},
     'services'),

    (r'^services/programming$',
     'core.views.programming',
     {},
     'programming'),

    (r'^services/consulting$',
     'core.views.consulting',
     {},
     'consulting'),

现在在您的 html 模板中(让我们看看咨询页面),您只需:

Now inside your html template (lets just look at consulting page) all you have to put is:

//consulting.html
{% load breadcrumbs %}

{% block breadcrumbs %}
{% breadcrumb_url 'Services' services %}
{% breadcrumb_url 'Consulting' consulting %}

{% endblock %}

如果您想在面包屑中使用某种自定义文本,并且不想链接它,您可以使用 breadcrumb 标签代替.

If you want to use some kind of custom text within the breadcrumb, and don't want to link it, you can use breadcrumb tag instead.

//consulting.html
{% load breadcrumbs %}

{% block breadcrumbs %}
  {% breadcrumb_url 'Services' services %}
  {% breadcrumb_url 'Consulting' consulting %}
  {% breadcrumb 'We are great!' %}  
{% endblock %}

在更复杂的情况下,您可能希望包含特定对象的 id,这也很容易做到.这是一个更现实的例子:

There are more involved situations where you might want to include an id of a particular object, which is also easy to do. This is an example that is more realistic:

{% load breadcrumbs %}

{% block breadcrumbs %}
{% breadcrumb_url 'Employees' employee_list %}
{% if employee.id %}
    {% breadcrumb_url employee.company.name company_detail employee.company.id %}
    {% breadcrumb_url employee.full_name employee_detail employee.id %}
    {% breadcrumb 'Edit Employee ' %}
{% else %}
    {% breadcrumb 'New Employee' %}
{% endif %}

{% endblock %}

DaGood 面包屑片段

提供两个模板标签以在您的 HTML 模板中使用:breadcrumb 和breadcrumb_url.第一个允许创建简单的 url,包含文本部分和 url 部分.或者只有未链接的文本(例如,作为面包屑路径中的最后一项).第二,实际上可以使用带参数的命名 url!此外,它需要一个标题作为第一个参数.

DaGood breadcrumbs snippet

Provides two template tags to use in your HTML templates: breadcrumb and breadcrumb_url. The first allows creating of simple url, with the text portion and url portion. Or only unlinked text (as the last item in breadcrumb trail for example). The second, can actually take the named url with arguments! Additionally it takes a title as the first argument.

这是一个模板标签文件,应该进入您的/templatetags 目录.

This is a templatetag file that should go into your /templatetags directory.

只需在方法 create_crumb 中更改图像的路径即可!

Just change the path of the image in the method create_crumb and you are good to go!

不要忘记在 html 模板的顶部 {% load breadcrumbs %}!

Don't forget to {% load breadcrumbs %} at the top of your html template!

from django import template
from django.template import loader, Node, Variable
from django.utils.encoding import smart_str, smart_unicode
from django.template.defaulttags import url
from django.template import VariableDoesNotExist

register = template.Library()

@register.tag
def breadcrumb(parser, token):
    """
    Renders the breadcrumb.
    Examples:
        {% breadcrumb "Title of breadcrumb" url_var %}
        {% breadcrumb context_var  url_var %}
        {% breadcrumb "Just the title" %}
        {% breadcrumb just_context_var %}

    Parameters:
    -First parameter is the title of the crumb,
    -Second (optional) parameter is the url variable to link to, produced by url tag, i.e.:
        {% url person_detail object.id as person_url %}
        then:
        {% breadcrumb person.name person_url %}

    @author Andriy Drozdyuk
    """
    return BreadcrumbNode(token.split_contents()[1:])


@register.tag
def breadcrumb_url(parser, token):
    """
    Same as breadcrumb
    but instead of url context variable takes in all the
    arguments URL tag takes.
        {% breadcrumb "Title of breadcrumb" person_detail person.id %}
        {% breadcrumb person.name person_detail person.id %}
    """

    bits = token.split_contents()
    if len(bits)==2:
        return breadcrumb(parser, token)

    # Extract our extra title parameter
    title = bits.pop(1)
    token.contents = ' '.join(bits)

    url_node = url(parser, token)

    return UrlBreadcrumbNode(title, url_node)


class BreadcrumbNode(Node):
    def __init__(self, vars):
        """
        First var is title, second var is url context variable
        """
        self.vars = map(Variable,vars)

    def render(self, context):
        title = self.vars[0].var

        if title.find("'")==-1 and title.find('"')==-1:
            try:
                val = self.vars[0]
                title = val.resolve(context)
            except:
                title = ''

        else:
            title=title.strip("'").strip('"')
            title=smart_unicode(title)

        url = None

        if len(self.vars)>1:
            val = self.vars[1]
            try:
                url = val.resolve(context)
            except VariableDoesNotExist:
                print 'URL does not exist', val
                url = None

        return create_crumb(title, url)


class UrlBreadcrumbNode(Node):
    def __init__(self, title, url_node):
        self.title = Variable(title)
        self.url_node = url_node

    def render(self, context):
        title = self.title.var

        if title.find("'")==-1 and title.find('"')==-1:
            try:
                val = self.title
                title = val.resolve(context)
            except:
                title = ''
        else:
            title=title.strip("'").strip('"')
            title=smart_unicode(title)

        url = self.url_node.render(context)
        return create_crumb(title, url)


def create_crumb(title, url=None):
    """
    Helper function
    """
    crumb = """<span class="breadcrumbs-arrow">""" 
            """<img src="/media/images/arrow.gif" alt="Arrow">""" 
            """</span>"""
    if url:
        crumb = "%s<a href='%s'>%s</a>" % (crumb, url, title)
    else:
        crumb = "%s&nbsp;&nbsp;%s" % (crumb, title)

    return crumb

这篇关于如何在 Django 模板中实现面包屑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆