Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added template tag. #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
*.pyc
.*.sw*
build
.idea/
breadcrumbs_sample/test.db
9 changes: 6 additions & 3 deletions breadcrumbs/breadcrumbs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe

BREADCRUMBS_AUTO_HOME = getattr(settings, 'BREADCRUMBS_AUTO_HOME', False)
BREADCRUMBS_HOME_TITLE = getattr(settings, 'BREADCRUMBS_HOME_TITLE', _(u'Home'))


class BreadcrumbsInvalidFormat(Exception):
"""
Expand Down Expand Up @@ -66,7 +69,7 @@ class Breadcrumbs(Singleton):
class or with get_breadcrumbs().
"""
__bds = []
__autohome = getattr(settings, 'BREADCRUMBS_AUTO_HOME', False)
__autohome = BREADCRUMBS_AUTO_HOME
__urls = []
__started = False

Expand All @@ -78,12 +81,12 @@ def __call__(self, *args, **kwargs):
def __fill_home(self):
# fill home if settings.BREADCRUMBS_AUTO_HOME is True
if self.__autohome and len(self.__bds) == 0:
home_title = getattr(settings, 'BREADCRUMBS_HOME_TITLE', _(u'Home'))
home_title = BREADCRUMBS_HOME_TITLE
self.__fill_bds((home_title, u"/"))

def _clean(self):
self.__bds = []
self.__autohome = getattr(settings, 'BREADCRUMBS_AUTO_HOME', False)
self.__autohome = BREADCRUMBS_AUTO_HOME
self.__urls = []
self.__fill_home()

Expand Down
12 changes: 12 additions & 0 deletions breadcrumbs/templates/breadcrumbs/partial/breadcrumb.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<div id='breadcrumb' class="breadcrumb">
{% for breadcrumb in breadcrumbs %}
<a href="{{ breadcrumb.url }}">{{ breadcrumb.name }}</a> {% if extras or extra %} &gt; {% endif %}
{% endfor %}
{% for name, url in extras %}
{% if forloop.first and breadcrumb %} &gt; {% endif %}
<a href="{{ url }}">{{ name }}</a> {% if not forloop.last or extra %} &gt; {% endif %}
{% endfor %}
{% if extra %}
<span> {{ extra }} </span>
{% endif %}
</div>
5 changes: 5 additions & 0 deletions breadcrumbs/templatetags/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#! coding: utf-8



__author__ = 'lgomez'
110 changes: 110 additions & 0 deletions breadcrumbs/templatetags/breadcrumb_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#! coding: utf-8
from django import template

register = template.Library()


#http://stackoverflow.com/questions/4356329/creating-a-python-dictionary-from-a-line-of-text/4356415#4356415
def pairwise(iterable):
#s -> (s0,s1), (s2,s3), (s4, s5), ...
a = iter(iterable)
return zip(a, a)


@register.inclusion_tag('breadcrumbs/partial/breadcrumb.html', takes_context=True)
def breadcrumbs(context, *args, **kwargs):
"""
This tag renders all breadcrumbs registered.
But you can pass some arguments too.

If you pass one parameter, it will be shown without an anchor, just what you write.
i.e.:
{% breadcrumb "profile" %} or {% breadcrumb my_context_var %} will print
each breadcrumb registered and "profile" or what is in 'my_context_var' variable.

e.g.: Registering two breadcrumb (see "utils.py" module):

{% breadcrumb "profile" %}
=>
<a href="http://eg1.example.com"> breadcrumb_1</a> &gt;
<a href="http://eg2.example.com"> breadcrumb_2</a> &gt;
<span> profile</span> &gt;

If you pass more that one parameter, it takes in pairs. The first must be the what you
want to show in the breadcrumb, and the second the url. If you pass a odd number of
parameters, the last must be a "name".
i.e.: You can do:
{% breadcrumb "my foos" list_link %} and
{% breadcrumb "my foos" list_link "foo_settings" %} and
{% breadcrumb "my foos" list_link "that foo" foo_url %} and
{% breadcrumb "my foos" list_link "that foo" foo_url "foo_settings" %} and so on

e.g.: For readability I supposed no another breadcrumbs, just what I wrote here.
But you can register breadcrumb and they will be shown before that:

{% url "foo_detail" foo.id as foo_url %}
{% url "foo_list" as list %}
{% breadcrumb "my foos" list "that foo" foo_url "foo_settings" %}
=>
<a href="{{ list }}"> my foos </a> &gt;
<a href="{{ foo_url }}"> that foo </a> &gt;
<a span> "foo_settings" </span> &gt;

If you pass the kwarg "unpack" with value True, the template tag only takes 2 arguments.
the first a iterable that contains tuple of (name, url,), and the second a extra argument,
Thar will be shown (just a "name")
i.e.:
{% breadcrumb my_context_var unpack=True %} or
{% breadcrumb my_context_var "settings_foo" unpack=True %}

e.g.:
In some class-based view:
# ...

class FooSettings(DetailView):
model = Foo
template = "foo_settings.html"

def get_context_data(self, **kwargs):
context = super(FooSettings, self).get_context_data(**kwargs)
context["list"] = ("my_foos", reverse("foos"),), ("foo", reverse("foo", args=[self.object.id,]),)
return context

# ...

In "foo_settings.html" template:

{% breadcrumb list unpack=True %}

"""
template_context = dict()
unpack = kwargs.get('unpack', False)
args_list = list(args)
extras = []
extra = None
args_len = len(args_list)

if unpack:
if args_len == 0:
raise TypeError("Tag breadcrumb takes at least one argument with 'unpack=True' option.")
iterable = args_list.pop(0)
try:
for arg in iterable:
extras.append(arg)
except TypeError as e:
raise TypeError("Tag breadcrumbs take a iterable like first parameter with 'unpack=True'. %s" % e)
args_len = len(args_list)

if args_len % 2 != 0:
extra = args_list.pop(-1)

for name, url in pairwise(args_list):
extras.append((name, url))

template_context['breadcrumbs'] = context['request'].breadcrumbs
template_context['extras'] = extras
template_context['extra'] = extra
return template_context


__author__ = 'lgomez'
45 changes: 45 additions & 0 deletions breadcrumbs/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,51 @@
from breadcrumbs import Breadcrumbs, BreadcrumbsNotSet
from django.conf import settings
from django.core.cache import cache
from breadcrumbs import BREADCRUMBS_AUTO_HOME, BREADCRUMBS_HOME_TITLE
from django.utils.translation import ugettext as _
import re

BREADCRUMBS_AUTO_HOME = getattr(settings, 'BREADCRUMBS_AUTO_HOME', False)
BREADCRUMBS_HOME_TITLE = getattr(settings, 'BREADCRUMBS_HOME_TITLE', _(u'Home'))

PAGE_MATCHES = getattr(settings, 'PAGE_MATCHES', dict())
#This must be a dictionary. The key are used like regular expression to match the url.
# The value will be shown in breadcrumb. See the template.
# PAGE_MATCHES = {
# r'/': u"Home",
# r'/foo/': u"Foo page"
# }


if BREADCRUMBS_AUTO_HOME:
PAGE_MATCHES.update({r'/': BREADCRUMBS_HOME_TITLE})


def register_referer(request):
"""
In any View, you can register the page where you come from.
It will be automatically matched PAGE_MATCHES with dictionary.
If it doesn't match, it wont be added to breadcrumbs
"""
referer = get_referrer(request)
if referer:
name = get_name_from_url(referer)
if name and (name != BREADCRUMBS_HOME_TITLE):
request.breadcrumbs(name, referer)


def get_referrer(request):
return request.META.get('HTTP_REFERER', None)


def get_name_from_url(url):
"""
If the url matched with any regex, then return the name of that page.
"""
for page_regex in PAGE_MATCHES:
if re.search(page_regex, url):
return PAGE_MATCHES[page_regex]
return None


def make_flatpages_cache_key():
Expand Down
4 changes: 3 additions & 1 deletion breadcrumbs_sample/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@
'django.contrib.flatpages',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'breadcrumbs_sample.webui'
'breadcrumbs_sample.webui',
'templatetag',
'breadcrumbs',
)

BREADCRUMBS_AUTO_HOME = True
Empty file.
3 changes: 3 additions & 0 deletions breadcrumbs_sample/templatetag/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
11 changes: 11 additions & 0 deletions breadcrumbs_sample/templatetag/templates/dynamic.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{% extends "index.html" %}
{% load breadcrumb_tags %}

{% block content %}
{% url "tag-index" as index_url %}

{% breadcrumbs "tag-index-page" index_url "dynamic-breadcrumb" %}

<p> You are generating dynamic breadcrumbs </p>
You can click on them!
{% endblock content %}
26 changes: 26 additions & 0 deletions breadcrumbs_sample/templatetag/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{% load breadcrumb_tags %}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% block content %}
{% breadcrumbs "breadcrumb-tag-index" %}

<p> You are on breadcrumb template tag page </p>
Click on some link and you will see the "index" breadcrumb.
{% endblock content %}

<a href="{% url "tag-index" %}">
<div>Tag index page</div>
</a>
<a href="{% url "dynamic" %}">
<div>Dynamic page and url</div>
</a>
<a href="{% url "unpacking" %}">
<div>Unpack of first parameter</div>
</a>

</body>
</html>
10 changes: 10 additions & 0 deletions breadcrumbs_sample/templatetag/templates/unpacking.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% extends "index.html" %}
{% load breadcrumb_tags %}

{% block content %}

{% breadcrumbs extra_params "unpacking-breadcrumb" unpack=True %}

<p> You are unpack breadcrumbs </p>
You can click on them!
{% endblock content %}
16 changes: 16 additions & 0 deletions breadcrumbs_sample/templatetag/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mind remove this file since it do nothing?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, sorry

This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""

from django.test import TestCase


class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
29 changes: 29 additions & 0 deletions breadcrumbs_sample/templatetag/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Create your views here.
from django.views.generic import TemplateView
from breadcrumbs.utils import register_referer


class IncludeReferer(TemplateView):
def get_context_data(self, **kwargs):
context = super(IncludeReferer, self).get_context_data(**kwargs)
register_referer(self.request) # Including the referer if it exists
return context


class IncludingDynamicURLs(IncludeReferer):
template_name = "dynamic.html"
pass


class UnpackingAVariableAndMore(IncludeReferer):
template_name = "unpacking.html"

def get_context_data(self, **kwargs):
context = super(UnpackingAVariableAndMore, self).get_context_data(**kwargs)
extra_params = ("name1", "example.com"), ("name2", "example2.com")
context["extra_params"] = extra_params
return context


class Index(TemplateView):
template_name = "index.html"
Binary file modified breadcrumbs_sample/test.db
Binary file not shown.
17 changes: 12 additions & 5 deletions breadcrumbs_sample/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,25 @@

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from breadcrumbs_sample.templatetag.views import Index, IncludingDynamicURLs, UnpackingAVariableAndMore

admin.autodiscover()

urlpatterns = patterns('',
urlpatterns = patterns(
'',
# Example:
# (r'^breadcrumbs_sample/', include('breadcrumbs_sample.foo.urls')),

# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^$','webui.views.home'),
(r'^someview/$','webui.views.someview'),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'webui.views.home',name="index"),
url(r'^someview/$', 'webui.views.someview'),
url(r'^index/$', Index.as_view(), name="tag-index"),
url(r'^dynamic/$', IncludingDynamicURLs.as_view(), name="dynamic"),
url(r'^unpacking/$', UnpackingAVariableAndMore.as_view(), name="unpacking"),

)