:members: Navigation, NavigationItem, NavigationMapper
:show-inheritance:
-Navigation caching
-------------------
-
.. autoclass:: NavigationManager
:members:
-.. autoclass:: NavigationItemManager
- :members:
-
-.. autoclass:: NavigationCacheQuerySet
- :members:
-
Template tags
+++++++++++++
<ul>
{% recursenavigation node "main" %}
<li{% if navloop.active %} class="active"{% endif %}>
- {{ item.text }}
+ <a href="{{ item.get_target_url }}">{{ item.text }}</a>
</li>
{% endrecursenavigation %}
</ul>
# or per-calendar-view basis.
#url(r'^%s/(?P<slug>[\w-]+)' % self.location_permalink_base, ...)
- if self.tag_archive_page:
+ if self.tag_archive_page_id:
urlpatterns += patterns('',
url(r'^%s$' % self.tag_permalink_base, self.tag_archive_view, name='tag_archive')
)
- if self.owner_archive_page:
+ if self.owner_archive_page_id:
urlpatterns += patterns('',
url(r'^%s$' % self.owner_permalink_base, self.owner_archive_view, name='owner_archive')
)
- if self.location_archive_page:
+ if self.location_archive_page_id:
urlpatterns += patterns('',
url(r'^%s$' % self.location_permalink_base, self.location_archive_view, name='location_archive')
)
def get_reverse_params(self, obj):
if isinstance(obj, BlogEntry):
- if obj.blog == self.blog:
+ if obj.blog_id == self.blog_id:
kwargs = {'slug': obj.slug}
if self.entry_permalink_style in 'DMY':
kwargs.update({'year': str(obj.date.year).zfill(4)})
elif isinstance(obj, Tag) or (isinstance(obj, models.query.QuerySet) and obj.model == Tag and obj):
if isinstance(obj, Tag):
obj = [obj]
- slugs = [tag.slug for tag in obj if tag in self.get_tag_queryset()]
+ slugs = [tag.slug for tag in obj if tag in self.get_tag_queryset(self.blog)]
if slugs:
return 'entries_by_tag', [], {'tag_slugs': "/".join(slugs)}
elif isinstance(obj, (date, datetime)):
urlpatterns = self.feed_patterns(r'^', 'get_all_entries', 'index_page', 'index') +\
self.feed_patterns(r'^%s/(?P<tag_slugs>[-\w]+[-+/\w]*)' % self.tag_permalink_base, 'get_entries_by_tag', 'tag_page', 'entries_by_tag')
- if self.tag_archive_page:
+ if self.tag_archive_page_id:
urlpatterns += patterns('',
url((r'^%s$' % self.tag_permalink_base), self.tag_archive_view, name='tag_archive')
)
- if self.entry_archive_page:
+ if self.entry_archive_page_id:
if self.entry_permalink_style in 'DMY':
urlpatterns += self.feed_patterns(r'^(?P<year>\d{4})', 'get_entries_by_ymd', 'entry_archive_page', 'entries_by_year')
if self.entry_permalink_style in 'DM':
def get_context(self):
return {'blog': self.blog}
- def get_entry_queryset(self):
+ def get_entry_queryset(self, obj):
"""Returns the default :class:`QuerySet` of :class:`BlogEntry` instances for the :class:`BlogView` - all entries that are considered posted in the past. This allows for scheduled posting of entries."""
- return self.blog.entries.filter(date__lte=datetime.now())
+ return obj.entries.filter(date__lte=datetime.now())
- def get_tag_queryset(self):
+ def get_tag_queryset(self, obj):
"""Returns the default :class:`QuerySet` of :class:`.Tag`\ s for the :class:`BlogView`'s :meth:`get_entries_by_tag` and :meth:`tag_archive_view`."""
- return self.blog.entry_tags
+ return obj.entry_tags
- def get_all_entries(self, request, extra_context=None):
+ def get_all_entries(self, obj, request, extra_context=None):
"""Used to generate :meth:`~.FeedView.feed_patterns` for all entries."""
- return self.get_entry_queryset(), extra_context
+ return self.get_entry_queryset(obj), extra_context
- def get_entries_by_ymd(self, request, year=None, month=None, day=None, extra_context=None):
+ def get_entries_by_ymd(self, obj, request, year=None, month=None, day=None, extra_context=None):
"""Used to generate :meth:`~.FeedView.feed_patterns` for entries with a specific year, month, and day."""
if not self.entry_archive_page:
raise Http404
- entries = self.get_entry_queryset()
+ entries = self.get_entry_queryset(obj)
if year:
entries = entries.filter(date__year=year)
if month:
context.update({'year': year, 'month': month, 'day': day})
return entries, context
- def get_entries_by_tag(self, request, tag_slugs, extra_context=None):
+ def get_entries_by_tag(self, obj, request, tag_slugs, extra_context=None):
"""Used to generate :meth:`~.FeedView.feed_patterns` for entries with all of the given tags."""
tag_slugs = tag_slugs.replace('+', '/').split('/')
- tags = self.get_tag_queryset().filter(slug__in=tag_slugs)
+ tags = self.get_tag_queryset(obj).filter(slug__in=tag_slugs)
if not tags:
raise Http404
if slug and slug not in found_slugs:
raise Http404
- entries = self.get_entry_queryset()
+ entries = self.get_entry_queryset(obj)
for tag in tags:
entries = entries.filter(tags=tag)
def entry_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
"""Renders :attr:`entry_page` with the entry specified by the given parameters."""
- entries = self.get_entry_queryset()
+ entries = self.get_entry_queryset(self.blog)
if year:
entries = entries.filter(date__year=year)
if month:
context = self.get_context()
context.update(extra_context or {})
context.update({
- 'tags': self.get_tag_queryset()
+ 'tags': self.get_tag_queryset(self.blog)
})
return self.tag_archive_page.render_to_response(request, extra_context=context)
def get_reverse_params(self, obj):
if isinstance(obj, NewsletterArticle):
- if obj.newsletter == self.newsletter:
+ if obj.newsletter_id == self.newsletter_id:
kwargs = {'slug': obj.slug}
if self.article_permalink_style in 'DMY':
kwargs.update({'year': str(obj.date.year).zfill(4)})
kwargs.update({'day': str(obj.date.day).zfill(2)})
return self.article_view, [], kwargs
elif isinstance(obj, NewsletterIssue):
- if obj.newsletter == self.newsletter:
+ if obj.newsletter_id == self.newsletter_id:
return 'issue', [], {'numbering': obj.numbering}
elif isinstance(obj, (date, datetime)):
kwargs = {
urlpatterns = self.feed_patterns(r'^', 'get_all_articles', 'index_page', 'index') + patterns('',
url(r'^%s/(?P<numbering>.+)$' % self.issue_permalink_base, self.page_view('get_articles_by_issue', 'issue_page'), name='issue')
)
- if self.issue_archive_page:
+ if self.issue_archive_page_id:
urlpatterns += patterns('',
url(r'^%s$' % self.issue_permalink_base, self.issue_archive_view, 'issue_archive')
)
- if self.article_archive_page:
+ if self.article_archive_page_id:
urlpatterns += self.feed_patterns(r'^%s' % self.article_permalink_base, 'get_all_articles', 'article_archive_page', 'articles')
if self.article_permalink_style in 'DMY':
urlpatterns += self.feed_patterns(r'^%s/(?P<year>\d{4})' % self.article_permalink_base, 'get_articles_by_ymd', 'article_archive_page', 'articles_by_year')
def get_context(self):
return {'newsletter': self.newsletter}
- def get_article_queryset(self):
+ def get_article_queryset(self, obj):
"""Returns the default :class:`QuerySet` of :class:`NewsletterArticle` instances for the :class:`NewsletterView` - all articles that are considered posted in the past. This allows for scheduled posting of articles."""
- return self.newsletter.articles.filter(date__lte=datetime.now())
+ return obj.articles.filter(date__lte=datetime.now())
- def get_issue_queryset(self):
+ def get_issue_queryset(self, obj):
"""Returns the default :class:`QuerySet` of :class:`NewsletterIssue` instances for the :class:`NewsletterView`."""
- return self.newsletter.issues.all()
+ return obj.issues.all()
- def get_all_articles(self, request, extra_context=None):
+ def get_all_articles(self, obj, request, extra_context=None):
"""Used to generate :meth:`~.FeedView.feed_patterns` for all entries."""
- return self.get_article_queryset(), extra_context
+ return self.get_article_queryset(obj), extra_context
- def get_articles_by_ymd(self, request, year, month=None, day=None, extra_context=None):
+ def get_articles_by_ymd(self, obj, request, year, month=None, day=None, extra_context=None):
"""Used to generate :meth:`~.FeedView.feed_patterns` for a specific year, month, and day."""
- articles = self.get_article_queryset().filter(date__year=year)
+ articles = self.get_article_queryset(obj).filter(date__year=year)
if month:
articles = articles.filter(date__month=month)
if day:
articles = articles.filter(date__day=day)
return articles, extra_context
- def get_articles_by_issue(self, request, numbering, extra_context=None):
+ def get_articles_by_issue(self, obj, request, numbering, extra_context=None):
"""Used to generate :meth:`~.FeedView.feed_patterns` for articles from a certain issue."""
try:
- issue = self.get_issue_queryset().get(numbering=numbering)
+ issue = self.get_issue_queryset(obj).get(numbering=numbering)
except NewsletterIssue.DoesNotExist:
raise Http404
context = extra_context or {}
context.update({'issue': issue})
- return self.get_article_queryset().filter(issues=issue), context
+ return self.get_article_queryset(obj).filter(issues=issue), context
def article_view(self, request, slug, year=None, month=None, day=None, extra_context=None):
"""Renders :attr:`article_page` with the article specified by the given parameters."""
- articles = self.get_article_queryset()
+ articles = self.get_article_queryset(self.newsletter)
if year:
articles = articles.filter(date__year=year)
if month:
context = self.get_context()
context.update(extra_context or {})
context.update({
- 'issues': self.get_issue_queryset()
+ 'issues': self.get_issue_queryset(self.newsletter)
})
return self.issue_archive_page.render_to_response(request, extra_context=context)
class NavigationItemInline(admin.StackedInline):
raw_id_fields = NAVIGATION_RAW_ID_FIELDS
model = NavigationItem
- extra = 1
+ extra = 0
sortable_field_name = 'order'
+ ordering = ('order',)
related_lookup_fields = {'fk': raw_id_fields}
class NodeNavigationInline(admin.TabularInline):
model = Navigation
- extra = 1
+ extra = 0
NodeAdmin.inlines = [NodeNavigationInline, NodeNavigationItemInline] + NodeAdmin.inlines
<ul>
{% recursenavigation node "main" %}
<li{% if navloop.active %} class='active'{% endif %}>
- {{ item.text }}
+ <a href="{{ item.get_target_url }}">{{ item.text }}</a>
{% if item.get_children %}
<ul>
{{ children }}
{% endrecursenavigation %}
</ul>
- .. note:: {% recursenavigation %} requires that the current :class:`HttpRequest` be present in the context as ``request``. The simplest way to do this is with the `request context processor`_. If this is installed with just the default template context processors, the entry in your settings file will look like this::
-
- TEMPLATE_CONTEXT_PROCESSORS = (
- # Defaults
- "django.contrib.auth.context_processors.auth",
- "django.core.context_processors.debug",
- "django.core.context_processors.i18n",
- "django.core.context_processors.media",
- "django.core.context_processors.static",
- "django.contrib.messages.context_processors.messages"
- ...
- "django.core.context_processors.request"
- )
+ .. note:: {% recursenavigation %} requires that the current :class:`HttpRequest` be present in the context as ``request``. The simplest way to do this is with the `request context processor`_. Simply make sure that ``django.core.context_processors.request`` is included in your :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
.. _request context processor: https://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request
+
"""
bits = token.contents.split()
if len(bits) != 3:
def urlpatterns(self):
urlpatterns = super(PasswordMultiView, self).urlpatterns
- if self.password_reset_page and self.password_reset_confirmation_email and self.password_set_page:
+ if self.password_reset_page_id and self.password_reset_confirmation_email_id and self.password_set_page_id:
urlpatterns += patterns('',
url(r'^password/reset$', csrf_protect(self.password_reset), name='password_reset'),
url(r'^password/reset/(?P<uidb36>\w+)/(?P<token>[^/]+)$', self.password_reset_confirm, name='password_reset_confirm'),
)
- if self.password_change_page:
+ if self.password_change_page_id:
urlpatterns += patterns('',
url(r'^password/change$', csrf_protect(self.login_required(self.password_change)), name='password_change'),
)
@property
def urlpatterns(self):
urlpatterns = super(RegistrationMultiView, self).urlpatterns
- if self.register_page and self.register_confirmation_email:
+ if self.register_page_id and self.register_confirmation_email_id:
urlpatterns += patterns('',
url(r'^register$', csrf_protect(self.register), name='register'),
url(r'^register/(?P<uidb36>\w+)/(?P<token>[^/]+)$', self.register_confirm, name='register_confirm')
@property
def urlpatterns(self):
urlpatterns = super(AccountMultiView, self).urlpatterns
- if self.manage_account_page:
+ if self.manage_account_page_id:
urlpatterns += patterns('',
url(r'^account$', self.login_required(self.account_view), name='account'),
)
- if self.email_change_confirmation_email:
+ if self.email_change_confirmation_email_id:
urlpatterns += patterns('',
url(r'^account/email/(?P<uidb36>\w+)/(?P<email>[\w.]+[+][\w.]+)/(?P<token>[^/]+)$', self.email_change_confirm, name='email_change_confirm')
)
"""
Returns a view function that renders a list of items as a feed.
- :param get_items_attr: A callable or the name of a callable on the :class:`FeedView` that will return a (items, extra_context) tuple when called with view arguments.
+ :param get_items_attr: A callable or the name of a callable on the :class:`FeedView` that will return a (items, extra_context) tuple when called with the object for the feed and view arguments.
:param reverse_name: The name which can be used reverse the page for this feed using the :class:`FeedView` as the urlconf.
:param feed_type: The slug used to render the feed class which will be used by the returned view function.
def inner(request, extra_context=None, *args, **kwargs):
obj = self.get_object(request, *args, **kwargs)
feed = self.get_feed(obj, request, reverse_name, feed_type, *args, **kwargs)
- items, xxx = get_items(request, extra_context=extra_context, *args, **kwargs)
+ items, xxx = get_items(obj, request, extra_context=extra_context, *args, **kwargs)
self.populate_feed(feed, items, request)
response = HttpResponse(mimetype=feed.mime_type)
page = page_attr if isinstance(page_attr, Page) else getattr(self, page_attr)
def inner(request, extra_context=None, *args, **kwargs):
- items, extra_context = get_items(request, extra_context=extra_context, *args, **kwargs)
+ obj = self.get_object(request, *args, **kwargs)
+ items, extra_context = get_items(obj, request, extra_context=extra_context, *args, **kwargs)
items, item_context = self.process_page_items(request, items)
context = self.get_context()
import mimetypes
from os.path import basename
+from django.conf import settings
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site, RequestSite
+from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.servers.basehttp import FileWrapper
from django.core.urlresolvers import resolve, clear_url_caches, reverse, NoReverseMatch
_view_content_type_limiter = ContentTypeSubclassLimiter(None)
+CACHE_PHILO_ROOT = getattr(settings, "PHILO_CACHE_PHILO_ROOT", True)
class Node(SlugTreeEntity):
Node urls will not contain a trailing slash unless a subpath is provided which ends with a trailing slash. Subpaths are expected to begin with a slash, as if returned by :func:`django.core.urlresolvers.reverse`.
+ Because this method will be called frequently and will always try to reverse ``philo-root``, the results of that reversal will be cached by default. This can be disabled by setting :setting:`PHILO_CACHE_PHILO_ROOT` to ``False``.
+
:meth:`construct_url` may raise the following exceptions:
- :class:`NoReverseMatch` if "philo-root" is not reversable -- for example, if :mod:`philo.urls` is not included anywhere in your urlpatterns.
"""
# Try reversing philo-root first, since we can't do anything if that fails.
- root_url = reverse('philo-root')
+ if CACHE_PHILO_ROOT:
+ key = "CACHE_PHILO_ROOT__" + settings.ROOT_URLCONF
+ root_url = cache.get(key)
+ if root_url is None:
+ root_url = reverse('philo-root')
+ cache.set(key, root_url)
+ else:
+ root_url = reverse('philo-root')
try:
current_site = Site.objects.get_current()
kwargs = dict([(smart_str(k, 'ascii'), v) for k, v in params.items()])
return self.url_or_subpath, args, kwargs
- def get_target_url(self):
- """Calculates and returns the target url based on the :attr:`target_node`, :attr:`url_or_subpath`, and :attr:`reversing_parameters`."""
+ def get_target_url(self, memoize=True):
+ """Calculates and returns the target url based on the :attr:`target_node`, :attr:`url_or_subpath`, and :attr:`reversing_parameters`. The results will be memoized by default; this can be prevented by passing in ``memoize=False``."""
+ if memoize:
+ memo_args = (self.target_node_id, self.url_or_subpath, self.reversing_parameters_json)
+ try:
+ return self._target_url_memo[memo_args]
+ except AttributeError:
+ self._target_url_memo = {}
+ except KeyError:
+ pass
+
node = self.target_node
if node is not None and node.accepts_subpath and self.url_or_subpath:
if self.reversing_parameters is not None:
subpath = self.url_or_subpath
if subpath[0] != '/':
subpath = '/' + subpath
- return node.construct_url(subpath)
+ target_url = node.construct_url(subpath)
elif node is not None:
- return node.get_absolute_url()
+ target_url = node.get_absolute_url()
else:
if self.reversing_parameters is not None:
view_name, args, kwargs = self.get_reverse_params()
- return reverse(view_name, args=args, kwargs=kwargs)
- return self.url_or_subpath
+ target_url = reverse(view_name, args=args, kwargs=kwargs)
+ else:
+ target_url = self.url_or_subpath
+
+ if memoize:
+ self._target_url_memo[memo_args] = target_url
+ return target_url
target_url = property(get_target_url)
class Meta:
"""
-import itertools
-
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.core.exceptions import ValidationError
from django.db import models
from django.http import HttpResponse
-from django.template import TemplateDoesNotExist, Context, RequestContext, Template as DjangoTemplate, TextNode, VariableNode
-from django.template.loader_tags import BlockNode, ExtendsNode, BlockContext
-from django.utils.datastructures import SortedDict
+from django.template import Context, RequestContext, Template as DjangoTemplate
from philo.models.base import SlugTreeEntity, register_value_model
from philo.models.fields import TemplateField
from philo.models.nodes import View
from philo.signals import page_about_to_render_to_string, page_finished_rendering_to_string
-from philo.templatetags.containers import ContainerNode
-from philo.utils import fattr
-from philo.validators import LOADED_TEMPLATE_ATTR
+from philo.utils import templates
__all__ = ('Template', 'Page', 'Contentlet', 'ContentReference')
-class LazyContainerFinder(object):
- def __init__(self, nodes, extends=False):
- self.nodes = nodes
- self.initialized = False
- self.contentlet_specs = []
- self.contentreference_specs = SortedDict()
- self.blocks = {}
- self.block_super = False
- self.extends = extends
-
- def process(self, nodelist):
- for node in nodelist:
- if self.extends:
- if isinstance(node, BlockNode):
- self.blocks[node.name] = block = LazyContainerFinder(node.nodelist)
- block.initialize()
- self.blocks.update(block.blocks)
- continue
-
- if isinstance(node, ContainerNode):
- if not node.references:
- self.contentlet_specs.append(node.name)
- else:
- if node.name not in self.contentreference_specs.keys():
- self.contentreference_specs[node.name] = node.references
- continue
-
- if isinstance(node, VariableNode):
- if node.filter_expression.var.lookups == (u'block', u'super'):
- self.block_super = True
-
- if hasattr(node, 'child_nodelists'):
- for nodelist_name in node.child_nodelists:
- if hasattr(node, nodelist_name):
- nodelist = getattr(node, nodelist_name)
- self.process(nodelist)
-
- # LOADED_TEMPLATE_ATTR contains the name of an attribute philo uses to declare a
- # node as rendering an additional template. Philo monkeypatches the attribute onto
- # the relevant default nodes and declares it on any native nodes.
- if hasattr(node, LOADED_TEMPLATE_ATTR):
- loaded_template = getattr(node, LOADED_TEMPLATE_ATTR)
- if loaded_template:
- nodelist = loaded_template.nodelist
- self.process(nodelist)
-
- def initialize(self):
- if not self.initialized:
- self.process(self.nodes)
- self.initialized = True
-
-
-def build_extension_tree(nodelist):
- nodelists = []
- extends = None
- for node in nodelist:
- if not isinstance(node, TextNode):
- if isinstance(node, ExtendsNode):
- extends = node
- break
-
- if extends:
- if extends.nodelist:
- nodelists.append(LazyContainerFinder(extends.nodelist, extends=True))
- loaded_template = getattr(extends, LOADED_TEMPLATE_ATTR)
- nodelists.extend(build_extension_tree(loaded_template.nodelist))
- else:
- # Base case: root.
- nodelists.append(LazyContainerFinder(nodelist))
- return nodelists
-
-
class Template(SlugTreeEntity):
"""Represents a database-driven django template."""
#: The name of the template. Used for organization and debugging.
#: An insecure :class:`~philo.models.fields.TemplateField` containing the django template code for this template.
code = TemplateField(secure=False, verbose_name='django template code')
- @property
- def containers(self):
+ def get_containers(self):
"""
Returns a tuple where the first item is a list of names of contentlets referenced by containers, and the second item is a list of tuples of names and contenttypes of contentreferences referenced by containers. This will break if there is a recursive extends or includes in the template code. Due to the use of an empty Context, any extends or include tags with dynamic arguments probably won't work.
"""
template = DjangoTemplate(self.code)
-
- # Build a tree of the templates we're using, placing the root template first.
- levels = build_extension_tree(template.nodelist)
-
- contentlet_specs = []
- contentreference_specs = SortedDict()
- blocks = {}
-
- for level in reversed(levels):
- level.initialize()
- contentlet_specs.extend(itertools.ifilter(lambda x: x not in contentlet_specs, level.contentlet_specs))
- contentreference_specs.update(level.contentreference_specs)
- for name, block in level.blocks.items():
- if block.block_super:
- blocks.setdefault(name, []).append(block)
- else:
- blocks[name] = [block]
-
- for block_list in blocks.values():
- for block in block_list:
- block.initialize()
- contentlet_specs.extend(itertools.ifilter(lambda x: x not in contentlet_specs, block.contentlet_specs))
- contentreference_specs.update(block.contentreference_specs)
-
- return contentlet_specs, contentreference_specs
+ return templates.get_containers(template)
+ containers = property(get_containers)
def __unicode__(self):
"""Returns the value of the :attr:`name` field."""
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
+from django.db.models import Q
from django.utils.safestring import SafeUnicode, mark_safe
register = template.Library()
+CONTAINER_CONTEXT_KEY = 'philo_container_context'
+
+
+class ContainerContext(object):
+ def __init__(self, page):
+ self.page = page
+
+ def get_contentlets(self):
+ if not hasattr(self, '_contentlets'):
+ self._contentlets = dict(((c.name, c) for c in self.page.contentlets.all()))
+ return self._contentlets
+
+ def get_references(self):
+ if not hasattr(self, '_references'):
+ references = self.page.contentreferences.all()
+ self._references = dict((((c.name, ContentType.objects.get_for_id(c.content_type_id)), c) for c in references))
+ return self._references
+
+
class ContainerNode(template.Node):
def __init__(self, name, references=None, as_var=None):
self.name = name
self.references = references
def render(self, context):
- content = settings.TEMPLATE_STRING_IF_INVALID
- if 'page' in context:
- container_content = self.get_container_content(context)
- else:
- container_content = None
+ container_content = self.get_container_content(context)
if self.as_var:
context[self.as_var] = container_content
return ''
- if not container_content:
- return ''
-
return container_content
def get_container_content(self, context):
- page = context['page']
+ try:
+ container_context = context.render_context[CONTAINER_CONTEXT_KEY]
+ except KeyError:
+ try:
+ page = context['page']
+ except KeyError:
+ return settings.TEMPLATE_STRING_IF_INVALID
+
+ container_context = ContainerContext(page)
+ context.render_context[CONTAINER_CONTEXT_KEY] = container_context
+
if self.references:
# Then it's a content reference.
try:
- contentreference = page.contentreferences.get(name__exact=self.name, content_type=self.references)
- content = contentreference.content
- except ObjectDoesNotExist:
+ contentreference = container_context.get_references()[(self.name, self.references)]
+ except KeyError:
content = ''
+ else:
+ content = contentreference.content
else:
# Otherwise it's a contentlet.
try:
- contentlet = page.contentlets.get(name__exact=self.name)
- if '{%' in contentlet.content or '{{' in contentlet.content:
- try:
- content = template.Template(contentlet.content, name=contentlet.name).render(context)
- except template.TemplateSyntaxError, error:
- if settings.DEBUG:
- content = ('[Error parsing contentlet \'%s\': %s]' % (self.name, error))
- else:
- content = settings.TEMPLATE_STRING_IF_INVALID
- else:
- content = contentlet.content
- except ObjectDoesNotExist:
- content = settings.TEMPLATE_STRING_IF_INVALID
- content = mark_safe(content)
+ contentlet = container_context.get_contentlets()[self.name]
+ except KeyError:
+ content = ''
+ else:
+ content = contentlet.content
return content
from django.contrib.contenttypes.models import ContentType
from django.template.loader_tags import ExtendsNode, BlockContext, BLOCK_CONTEXT_KEY, TextNode, BlockNode
-from philo.utils import LOADED_TEMPLATE_ATTR
+from philo.utils.templates import LOADED_TEMPLATE_ATTR
register = template.Library()
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage
-from django.template import Context
-from django.template.loader_tags import ExtendsNode, ConstantIncludeNode
def fattr(*args, **kwargs):
else:
objects = page.object_list
- return paginator, page, objects
-
-
-### Facilitating template analysis.
-
-
-LOADED_TEMPLATE_ATTR = '_philo_loaded_template'
-BLANK_CONTEXT = Context()
-
-
-def get_extended(self):
- return self.get_parent(BLANK_CONTEXT)
-
-
-def get_included(self):
- return self.template
-
-
-# We ignore the IncludeNode because it will never work in a blank context.
-setattr(ExtendsNode, LOADED_TEMPLATE_ATTR, property(get_extended))
-setattr(ConstantIncludeNode, LOADED_TEMPLATE_ATTR, property(get_included))
\ No newline at end of file
+ return paginator, page, objects
\ No newline at end of file
--- /dev/null
+import itertools
+
+from django.template import TextNode, VariableNode, Context
+from django.template.loader_tags import BlockNode, ExtendsNode, BlockContext, ConstantIncludeNode
+from django.utils.datastructures import SortedDict
+
+from philo.templatetags.containers import ContainerNode
+
+
+LOADED_TEMPLATE_ATTR = '_philo_loaded_template'
+BLANK_CONTEXT = Context()
+
+
+def get_extended(self):
+ return self.get_parent(BLANK_CONTEXT)
+
+
+def get_included(self):
+ return self.template
+
+
+# We ignore the IncludeNode because it will never work in a blank context.
+setattr(ExtendsNode, LOADED_TEMPLATE_ATTR, property(get_extended))
+setattr(ConstantIncludeNode, LOADED_TEMPLATE_ATTR, property(get_included))
+
+
+def get_containers(template):
+ # Build a tree of the templates we're using, placing the root template first.
+ levels = build_extension_tree(template.nodelist)
+
+ contentlet_specs = []
+ contentreference_specs = SortedDict()
+ blocks = {}
+
+ for level in reversed(levels):
+ level.initialize()
+ contentlet_specs.extend(itertools.ifilter(lambda x: x not in contentlet_specs, level.contentlet_specs))
+ contentreference_specs.update(level.contentreference_specs)
+ for name, block in level.blocks.items():
+ if block.block_super:
+ blocks.setdefault(name, []).append(block)
+ else:
+ blocks[name] = [block]
+
+ for block_list in blocks.values():
+ for block in block_list:
+ block.initialize()
+ contentlet_specs.extend(itertools.ifilter(lambda x: x not in contentlet_specs, block.contentlet_specs))
+ contentreference_specs.update(block.contentreference_specs)
+
+ return contentlet_specs, contentreference_specs
+
+
+class LazyContainerFinder(object):
+ def __init__(self, nodes, extends=False):
+ self.nodes = nodes
+ self.initialized = False
+ self.contentlet_specs = []
+ self.contentreference_specs = SortedDict()
+ self.blocks = {}
+ self.block_super = False
+ self.extends = extends
+
+ def process(self, nodelist):
+ for node in nodelist:
+ if self.extends:
+ if isinstance(node, BlockNode):
+ self.blocks[node.name] = block = LazyContainerFinder(node.nodelist)
+ block.initialize()
+ self.blocks.update(block.blocks)
+ continue
+
+ if isinstance(node, ContainerNode):
+ if not node.references:
+ self.contentlet_specs.append(node.name)
+ else:
+ if node.name not in self.contentreference_specs.keys():
+ self.contentreference_specs[node.name] = node.references
+ continue
+
+ if isinstance(node, VariableNode):
+ if node.filter_expression.var.lookups == (u'block', u'super'):
+ self.block_super = True
+
+ if hasattr(node, 'child_nodelists'):
+ for nodelist_name in node.child_nodelists:
+ if hasattr(node, nodelist_name):
+ nodelist = getattr(node, nodelist_name)
+ self.process(nodelist)
+
+ # LOADED_TEMPLATE_ATTR contains the name of an attribute philo uses to declare a
+ # node as rendering an additional template. Philo monkeypatches the attribute onto
+ # the relevant default nodes and declares it on any native nodes.
+ if hasattr(node, LOADED_TEMPLATE_ATTR):
+ loaded_template = getattr(node, LOADED_TEMPLATE_ATTR)
+ if loaded_template:
+ nodelist = loaded_template.nodelist
+ self.process(nodelist)
+
+ def initialize(self):
+ if not self.initialized:
+ self.process(self.nodes)
+ self.initialized = True
+
+
+def build_extension_tree(nodelist):
+ nodelists = []
+ extends = None
+ for node in nodelist:
+ if not isinstance(node, TextNode):
+ if isinstance(node, ExtendsNode):
+ extends = node
+ break
+
+ if extends:
+ if extends.nodelist:
+ nodelists.append(LazyContainerFinder(extends.nodelist, extends=True))
+ loaded_template = getattr(extends, LOADED_TEMPLATE_ATTR)
+ nodelists.extend(build_extension_tree(loaded_template.nodelist))
+ else:
+ # Base case: root.
+ nodelists.append(LazyContainerFinder(nodelist))
+ return nodelists
\ No newline at end of file
from django.utils.html import escape, mark_safe
from django.utils.translation import ugettext_lazy as _
-from philo.utils import LOADED_TEMPLATE_ATTR
+from philo.utils.templates import LOADED_TEMPLATE_ATTR
#: Tags which are considered insecure and are therefore always disallowed by secure :class:`TemplateValidator` instances.