hakanw avatar hakanw committed 969e9f3

Initial add of existing django-chunks trunk

Comments (0)

Files changed (9)

+django-chunks was originally developed by Clint Ecker
+
+Caching code suggested by Kevin Fricovsky (howiworkdaily.com)
+Copyright (c) 2008, Clint Ecker
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without 
+modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this 
+list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or 
+other materials provided with the distribution.
+
+Neither the name of the <ORGANIZATION> nor the names of its contributors may 
+be used to endorse or promote products derived from this software without 
+specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+Think of it as flatpages for small bits of reusable content you might want to 
+insert into your templates and manage from the admin interface.
+
+This is really nothing more than a model and a template tag.
+
+By adding `chunks` to your installed apps list in your Django project and 
+performing a `./manage.py syncdb`, you'll be able to add as many "keyed" bits 
+of content chunks to your site.
+
+The idea here is that you can create a chunk of content, name it with a unique
+key (for example: `home_page_left_bottom`) and then you can call this content 
+from a normal template.
+
+Why would anyone want this?
+
+It essentially allows someone to define "chunks" (I had wanted to call it
+ blocks, but that would be very confusing for obvious reasons) of content in 
+your template that can be directly edited from the awesome Django admin 
+interface.  Throwing a rich text editor control on top of it make it even 
+easier.
+
+Template tag usage:
+
+{% load chunks %}
+<html>
+    <head>
+        <title>Test</title>
+    </head>
+    <body>
+        <h1> Blah blah blah</h1>
+        <div id="sidebar">
+            ...
+        </div>
+        <div id="left">
+            {% chunk "home_page_left" %}
+        </div>
+        <div id="right">
+            {% chunk "home_page_right" %}
+        </div>
+    </body>
+</html>
+
+This is really helpful in those cases where you want to use 
+`django.contrib.flatpages` but you need multiple content areas.  I hope this 
+is helpful to people and I'll be making minor edits as I see them necessary.
+
+Caching
+
+If you want to cache the content of your chunks you can pass along a caching
+time argument in your chunk tag.  Example:
+
+{% chunk "home_page_left" 3600 %}
+
+The caching time is specified in seconds.  For caching to work properly you 
+must configure a cache backend in your settings.py.  See the Django
+documentation for more information:
+
+http://www.djangoproject.com/documentation/cache/

Empty file added.

+from django.contrib import admin
+from models import Chunk
+
+class ChunkAdmin(admin.ModelAdmin):
+  list_display = ('key',)
+  search_fields = ('key', 'content')
+
+admin.site.register(Chunk, ChunkAdmin)
+from django.db import models
+
+class Chunk(models.Model):
+    """
+    A Chunk is a piece of content associated
+    with a unique key that can be inserted into
+    any template with the use of a special template
+    tag
+    """
+    key = models.CharField(help_text="A unique name for this chunk of content", blank=False, max_length=255, unique=True)
+    content = models.TextField(blank=True)
+
+    def __unicode__(self):
+        return u"%s" % (self.key,)
Add a comment to this file

chunks/templatetags/__init__.py

Empty file added.

chunks/templatetags/chunks.py

+from django import template
+from django.db import models
+from django.core.cache import cache
+
+register = template.Library()
+
+Chunk = models.get_model('chunks', 'chunk')
+CACHE_PREFIX = "chunk_"
+
+def do_get_chunk(parser, token):
+    # split_contents() knows not to split quoted strings.
+    tokens = token.split_contents()
+    if len(tokens) < 2 or len(tokens) > 3:
+        raise template.TemplateSyntaxError, "%r tag should have either 2 or 3 arguments" % (tokens[0],)
+    if len(tokens) == 2:
+        tag_name, key = tokens
+        cache_time = 0
+    if len(tokens) == 3:
+        tag_name, key, cache_time = tokens
+    # Check to see if the key is properly double/single quoted
+    if not (key[0] == key[-1] and key[0] in ('"', "'")):
+        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
+    # Send key without quotes and caching time
+    return ChunkNode(key[1:-1], cache_time)
+    
+class ChunkNode(template.Node):
+    def __init__(self, key, cache_time=0):
+       self.key = key
+       self.cache_time = cache_time
+    
+    def render(self, context):
+        try:
+            cache_key = CACHE_PREFIX + self.key
+            c = cache.get(cache_key)
+            if c is None:
+                c = Chunk.objects.get(key=self.key)
+                cache.set(cache_key, c, int(self.cache_time))
+            content = c.content
+        except Chunk.DoesNotExist:
+            content = ''
+        return content
+        
+register.tag('chunk', do_get_chunk)
+from distutils.core import setup
+
+setup(name='chunks',
+      version='0.1',
+      description='Keyed blocks of content for use in your Django templates',
+      author='Clint Ecker',
+      author_email='me@clintecker.com',
+      url='http://code.google.com/p/django-chunks/',
+      packages=['chunks', 'chunks.templatetags'],
+      classifiers=['Development Status :: 4 - Beta',
+                   'Environment :: Web Environment',
+                   'Intended Audience :: Developers',
+                   'License :: OSI Approved :: BSD License',
+                   'Operating System :: OS Independent',
+                   'Programming Language :: Python',
+                   'Topic :: Utilities'],
+      )
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.