whitespaceoptimize block tag

 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
# python
from slimmer import guessSyntax, css_slimmer, html_slimmer, js_slimmer

# django
from django import template
    
class WhitespaceOptimizeNode(template.Node):
    def __init__(self, nodelist, format=None):
        self.nodelist = nodelist
        self.format = format
    def render(self, context):
        code = self.nodelist.render(context)
        if self.format == 'css':
            return css_slimmer(code)
        elif self.format in ('js', 'javascript'):
            return js_slimmer(code)
        elif self.format == 'html':
            return html_slimmer(code)
        else:
            format = guessSyntax(code)
            if format:
                self.format = format
                return self.render(context)
    
        return code
    
register = template.Library()
@register.tag(name='whitespaceoptimize')
def do_whitespaceoptimize(parser, token):
    nodelist = parser.parse(('endwhitespaceoptimize',))
    parser.delete_first_token()

    _split = token.split_contents()
    format = ''
    if len(_split) > 1:
        tag_name, format = _split
        if not (format[0] == format[-1] and format[0] in ('"', "'")):
            raise template.TemplateSyntaxError, \
                    "%r tag's argument should be in quotes" % tag_name

    return WhitespaceOptimizeNode(nodelist, format[1:-1])

More like this

  1. YUI Loader as Django middleware by akaihola 6 years ago
  2. really spaceless (trim spaces at line start) by wolfram 6 years, 3 months ago
  3. Cacheable resources by jbrisbin 5 years, 8 months ago
  4. Code syntax highlighting templatetag by badrunner 6 years, 7 months ago
  5. smart spaceless by nedbatchelder 6 years, 1 month ago

Comments

peterbe (on September 14, 2008):

The slimmer is very fast but will nevertheless cost a few milliseconds on each slimming. Adding a memoize pattern shouldn't be too hard. However, you have to keep in mind that the reason for doing this is not to obscure css, js or html but to make the downloadable object smaller which would save bandwidth.

#

(Forgotten your password?)