Ticket #6932: 6932-template-tag-for-flatpages-2.diff

File 6932-template-tag-for-flatpages-2.diff, 11.1 KB (added by faldridge, 5 years ago)
  • django/contrib/flatpages/tests/__init__.py

     
     1import os
     2
     3from django.conf import settings
     4from django.contrib.auth.models import AnonymousUser, User
     5from django.http import HttpRequest
     6from django.template import Template, Context
     7from django.test import TestCase
     8from django.contrib.flatpages.models import FlatPage
     9from django.contrib.flatpages.middleware import FlatpageFallbackMiddleware
     10from django.contrib.sites.models import Site
     11
     12
     13class FlatpageTests(TestCase):
     14    def setUp(self):
     15        self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
     16        settings.TEMPLATE_DIRS = (
     17            os.path.join(
     18                os.path.dirname(__file__),
     19                'templates'
     20            )
     21        ,)
     22
     23        page = FlatPage(
     24            url='/page1/',
     25            title='Some page',
     26            content="<p>Some text that shouldn't be automatically escaped</p>",
     27            registration_required=False,
     28            )
     29        page.save()
     30        page.sites.add(Site.objects.get_current())
     31        page.save()
     32
     33        registrationPage = FlatPage(
     34            url='/registered/page2/',
     35            title='Secret page',
     36            content="<p>Great, you are registered</p>",
     37            registration_required=True,
     38            )
     39        registrationPage.save()
     40        registrationPage.sites.add(Site.objects.get_current())
     41        registrationPage.save()
     42
     43    def tearDown(self):
     44        settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS
     45
     46    def render(self, t, **c):
     47        ctx = Context(c)
     48        out = Template(t).render(ctx)
     49        return ctx, out
     50
     51    def testFlatpage(self):
     52        original_response = self.client.get('/page1/')
     53        fake_request = HttpRequest()
     54        fake_request.path_info = original_response.request['PATH_INFO']
     55        flatpage = FlatpageFallbackMiddleware().process_response(fake_request,
     56            original_response)
     57        self.assertContains(flatpage,
     58            "<p>Some text that shouldn't be automatically escaped</p>")
     59
     60    def testRegistrationRequiredRedirect(self):
     61        original_response = self.client.get('/registered/page2/')
     62        fake_request = HttpRequest()
     63        fake_request.path = original_response.request['PATH_INFO']
     64        fake_request.path_info = original_response.request['PATH_INFO']
     65        fake_request.user = AnonymousUser()
     66        flatpage = FlatpageFallbackMiddleware().process_response(fake_request,
     67            original_response)
     68        self.assertEquals(flatpage.status_code, 302)
     69        self.assertEquals(flatpage['Location'],
     70                          '/accounts/login/?next=/registered/page2/')
     71
     72    def testRegistrationRequiredRender(self):
     73        self.client.login(username='testuser', password='testpw')
     74        original_response = self.client.get('/registered/page2/')
     75        fake_request = HttpRequest()
     76        fake_request.path = original_response.request['PATH_INFO']
     77        fake_request.path_info = original_response.request['PATH_INFO']
     78        fake_request.user = User.objects.create_user('testuser',
     79            'test@example.com', 'testpw')
     80        flatpage = FlatpageFallbackMiddleware().process_response(fake_request,
     81            original_response)
     82        self.assertContains(flatpage, "<p>Great, you are registered</p>")
     83
     84    def testGetFlatpagesTag(self):
     85        ctx, out = self.render("{% load flatpages %}"
     86                               "{% get_flatpages as flatpages %}"
     87                               "{% for page in flatpages %}"
     88                               "{{ page.title }},"
     89                               "{% endfor %}")
     90        self.assertEquals(out, "Some page,Secret page,")
     91
     92    def testGetFlatpagesTagUsingStartsWithString(self):
     93        ctx, out = self.render(
     94                "{% load flatpages %}"
     95                "{% get_flatpages '/registered/' as registered_flatpages %}"
     96                "{% for page in registered_flatpages %}"
     97                "{{ page.title }},"
     98                "{% endfor %}")
     99        self.assertEquals(out, "Secret page,")
     100
     101    def testGetFlatpagesTagUsingStartsWithVariable(self):
     102        ctx, out = self.render(
     103                "{% load flatpages %}"
     104                "{% get_flatpages registered_prefix as registered_flatpages %}"
     105                "{% for page in registered_flatpages %}"
     106                "{{ page.title }},"
     107                "{% endfor %}",
     108                registered_prefix='/registered/')
     109        self.assertEquals(out, "Secret page,")
  • django/contrib/flatpages/tests/templates/flatpages/default.html

     
     1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
     2    "http://www.w3.org/TR/REC-html40/loose.dtd">
     3<html>
     4<head>
     5<title>{{ flatpage.title }}</title>
     6</head>
     7<body>
     8{{ flatpage.content }}
     9</body>
     10</html>
  • django/contrib/flatpages/tests/templates/404.html

     
     1<p>Not Found</p>
  • django/contrib/flatpages/templatetags/__init__.py

     
     1
     2
  • django/contrib/flatpages/templatetags/flatpages.py

     
     1from django import template
     2from django.contrib.flatpages.models import FlatPage
     3from django.utils.translation import ugettext as _
     4from django.conf import settings
     5
     6
     7register = template.Library()
     8
     9
     10class FlatpageNode(template.Node):
     11    def __init__(self, context_name, starts_with=None):
     12        self.context_name, self.starts_with = context_name, starts_with
     13        if self.starts_with:
     14            self.starts_with = template.Variable(starts_with)
     15
     16    def render(self, context):
     17        flatpages = FlatPage.objects.filter(sites__id=settings.SITE_ID)
     18        if self.starts_with:
     19            flatpages = flatpages.filter(
     20                url__startswith=self.starts_with.resolve(context))
     21        context[self.context_name] = flatpages
     22        return ''
     23
     24
     25def get_flatpages(parser, token):
     26    """
     27    Retrieves all flatpage objects available for the current site and
     28    populates the template context with them in a variable whose name
     29    is defined by the 'as' clause.
     30
     31    An optional argument, ``starts_with``, can be applied to limit the
     32    returned flatpages to those beginning with a particular base URL.
     33    This argument can be passed as a variable or a string, as it resolves
     34    from the template context.
     35
     36    Syntax::
     37
     38        {% get_flatpages ['url_starts_with'] as context_name %}
     39
     40    Example usage::
     41
     42        {% get_flatpages as flatpages %}
     43        {% get_flatpages '/about/' as about_pages %}
     44        {% get_flatpages about_prefix as about_pages %}
     45    """
     46    bits = token.split_contents()
     47    if len(bits) is 3:
     48        if bits[1] != 'as':
     49            raise template.TemplateSyntaxError, _("%s expects a syntax of %s "
     50                "['url_starts_with'] as context_name" % (bits[0], bits[0]))
     51        return FlatpageNode(bits[2])
     52    elif len(bits) is 4:
     53        if bits[2] != 'as':
     54            raise template.TemplateSyntaxError, _("%s expects a syntax of %s "
     55                "['url_starts_with'] as context_name" % (bits[0], bits[0]))
     56        return FlatpageNode(bits[3], bits[1])
     57    else:
     58        raise template.TemplateSyntaxError, _("%s expects a syntax of %s "
     59            "['url_starts_with'] as context_name" % (bits[0], bits[0]))
     60
     61register.tag('get_flatpages', get_flatpages)
  • docs/ref/contrib/flatpages.txt

     
    167167both ``flatpage.title`` and ``flatpage.content`` are marked as **not**
    168168requiring :ref:`automatic HTML escaping <automatic-html-escaping>` in the
    169169template.
     170
     171Getting a list of :class:`~django.contrib.flatpages.models.Flatpage` objects in your templates
     172==============================================================================================
     173
     174.. versionadded:: 1.3
     175
     176The flatpages app also comes with a template tag that allows you to iterate
     177over all of the available flatpages on the :ref:`current site <hooking-into-current-site-from-views>`.
     178
     179Like all custom template tags, you'll need to :ref:`load its custom
     180tag library <loading-custom-template-libraries>` before you can use it:
     181
     182.. code-block:: html+django
     183
     184    {% load flatpages %}
     185
     186After loading the library, you can retrieve all current flatpages via the
     187:ttag:`get_flatpages` tag:
     188
     189.. code-block:: html+django
     190
     191    {% get_flatpages as flatpages %}
     192    <ul>
     193        {% for page in flatpages %}
     194            <li><a href="{{ page.url }}">{{ page.title }}</a></li>
     195        {% endfor %}
     196    </ul>
     197
     198Limiting flatpages by base URL
     199------------------------------
     200
     201An optional argument, ``starts_with``, can be applied to limit the
     202returned pages to those beginning with a particular base URL.  This argument
     203may be passed as a string or a variable, as it is resolved from the context:
     204
     205.. code-block:: html+django
     206
     207    {% get_flatpages ['url_starts_with'] as context_name %}
     208
     209For example:
     210
     211.. code-block:: html+django
     212
     213    {% get_flatpages '/about/' as about_pages %}
     214    {% get_flatpages about_prefix as about_pages %}
     215
     216Only displaying flatpages accessible to anonymous users
     217-------------------------------------------------------
     218
     219If you wish to filter flatpages out by :attr:`registration_required`, you
     220can place an if statement around your for loop:
     221
     222.. code-block:: html+django
     223
     224    {% get_flatpages '/contact/' as contact_pages %}
     225    {% for page in contact_pages %}
     226        {% if not user.is_authenticated and page.registration_required %}
     227            <h3><a href="{{page.url}}">{{page.title}}</a></h3>
     228        {% endif %}
     229    {% endfor %}
  • docs/ref/contrib/sites.txt

     
    104104
    105105This has the same benefits as described in the last section.
    106106
     107.. _hooking-into-current-site-from-views:
     108
    107109Hooking into the current site from views
    108110----------------------------------------
    109111
Back to Top