Login

Plaintext format (advanced spaceless)

Author:
hoverhell
Posted:
April 9, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

A template loader useful for writing templates with carefully controlled newlines and spaces while retaining readable template source code formatting.

Start the template with PTFTAG ({#ptfable#}, here) to allow it to be processed. Common problems with doing it to most templates as-is is use of newlines to separate words and multiple spaces between tags where spaces are still needed (which is problematic with spaceless tag as well).

Currently intended as a template loader wrapper, and is suggested to be used with cached loader. Example settings.py configuration:

_lp = lambda lo, *ar: (lo, ar,)  # loader, arguments
TEMPLATE_LOADERS = (
  _lp('django.template.loaders.cached.Loader',  # cache
    _lp('ptf.template.ptftemplateloader.Loader',  # ptf
     'django.template.loaders.filesystem.Loader',
     'django.template.loaders.app_directories.Loader',
     #'django.template.loaders.eggs.load_template_source'
    ),  # ptf
  ),  # cache
)

(change ptf. to wherever in python path you've put it).

You might also need couple of simple template tags for explicitly inserting newlines or whitespaces:

def br():
    return "\n"
br = register.simple_tag(br)
# XHTML-XMPP-template compatible.
def brx():
    return "<br />\n"
brx = register.simple_tag(br)
def ws():
    return " "
ws = register.simple_tag(ws)

.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
""" Wrapper for loading plaintextformat templates from the filesystem, e.g. 
with stripping unnecessary newlines and spaces from it.  """

import re
import sys  # Debug

from django.template import TemplateDoesNotExist
from django.template.loader import (BaseLoader, get_template_from_string,
  find_template_loader, make_origin)

## Start templates with this to actually ptf them:
PTFTAG = u'{#ptfable#}'
PTFTAGLEN = len(PTFTAG)
# Another way:
#tagspacere = re.compile('}\s\s+{')
SPACERE = re.compile('\s\s+')
NEWLINERE = re.compile('\n')

class Loader(BaseLoader):
    is_usable = True
    
    ## Stuff grabbed from django cache loader.
    def __init__(self, loaders):
        self._loaders = loaders
        self._cached_loaders = []
    
    # loaders = django.template.loaders.cached.Loader.loaders
    @property
    def loaders(self):
        # Resolve loaders on demand to avoid circular imports
        if not self._cached_loaders:
            for loader in self._loaders:
                self._cached_loaders.append(find_template_loader(loader))
        return self._cached_loaders

    # find_template = django.template.loaders.cached.Loader.find_template
    def find_template(self, name, dirs=None):
        for loader in self.loaders:
            try:
                template, display_name = loader.load_template_source(name, dirs)
                return (template, make_origin(display_name, loader, name, dirs))
            except TemplateDoesNotExist:
                pass
        raise TemplateDoesNotExist(name)

    def load_template_source(self, template_name, template_dirs=None):
        template, origin = self.find_template(template_name, template_dirs)
        ## Hack it up only if tagged.
        if template.startswith(PTFTAG):
            template = SPACERE.sub(u'',
              NEWLINERE.sub(u'', template[PTFTAGLEN:]))
            # Removing tag is optional if it's valid template, though.
        return (template, origin)
    load_template_source.is_usable = True

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.