Plaintext format (advanced spaceless)

 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. Smart Spaceless by btaylordesign 3 years ago
  2. really spaceless (trim spaces at line start) by wolfram 6 years, 3 months ago
  3. template + cache = crazy delicious by jacobian 6 years, 11 months ago
  4. smart spaceless by nedbatchelder 6 years, 1 month ago
  5. Simple template tag to do |stringformat filter with format from a variable by leopd 3 years ago

Comments

(Forgotten your password?)