Login

Showell markup--DRY up your templates

Author:
showell
Posted:
November 27, 2009
Language:
Python
Version:
1.1
Score:
1 (after 3 ratings)

The code shown implements a preprocessor for Django templates to support indentation-based syntax.

The pre-markup language is called Showell Markup. It allows you to remove lots of close tags and random punctuation. It also has a syntax for cleaning up individual lines of HTML with a pipe syntax for clearly separating content from markup. You can read the docstrings to glean the interface.

Here are examples:

>> table
    >> tr
        >> td
            Right
        >> td
            Center
        >> td
            Left

>> div class="spinnable"
    >> ul
        >> li id="item1"
            One
        >> li id="item2"
           Two

%% extends 'base.html'
%% load smartif

%% block body
    %% for book in books
        {{ book }}

    %% if condition
        Display this
    %% elif condition
        Display that
    %% else
        %% include 'other.html'

    >> tr class="header_row"
        Original Author | th class="first_column"
        Commenters      | th
        Title           | th
        Action          | th
        Last words      | th
        By              | th
        When            | th

    >> ol class="boring_list"
        One                      | li
        Two                      | li
        Three                    | li
        {{ element4|join:',' }}  | li

    Hello World!   | b | span class="greeting" ; br
    Goodbye World! | i | span class="parting_words"; br
    ; hr
    >> p class="praise"
        Indentation-based syntax is so
        Pythonic!

    Archive        LINK collection.archive referral.pk
    Home           LINK home.home
    Friends        LINK friendship.friends
    Create a card  LINK referrals.create
    Recent changes LINK activity.recent_changes

    >> FORM referrals.create
        {{ form.as_p }}
        {{ referral.id } | HIDDEN referral
  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
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
    import re

    def publish(master_fn):
        '''
        We use one master file that contains all the Showell markup, and 
        then we publish to Django templates.

        master_fn should be the name of a file that has several sections
        with banners like you get from the unix "more" command...

        ::::::::::::::
        ./apps/comment/templates/comment_form.html
        ::::::::::::::
        [some markup to be preprocessed]

        Each section of the master file gets converted and written to
        the output file. 
        '''
        f = open(master_fn)
        fn = body = None
        while True:
            line = f.readline()
            if not line: break
            if line.startswith('::::'):
                if fn:
                    convert(fn, body)
                fn = f.readline().strip()
                f.readline()
                body = ''
            else:
                body += line
        convert(fn, body)

    def convert(fn, in_body):
        out_body = convert_text(in_body)
        open(fn, 'w').write(out_body)

    def convert_text(in_body):
        '''
        You can call convert_text directly to convert Showell markup
        to HTML/Django markup.
        '''
        lines = []
        indenter = Indenter()
        for line in in_body.split('\n'):
            m = re.match('(\s*)(.*\S)(.*)', line)
            if m:
                prefix, line, cruft = m.groups()
                if line.startswith('>>'):
                    block_tag(prefix, line, indenter)
                elif line.startswith('%%'):
                    django_block(prefix, line, indenter)
                elif line.startswith('DEDENT'):
                    indenter.dedent()
                elif line.startswith('END_DEDENT'):
                    indenter.end_dedent(prefix)
                else:
                    line = fix_line(line)
                    indenter.add(prefix, line+cruft)
            else:
                indenter.add('', line)
        return indenter.body()

    def block_tag(prefix, line, indenter):
        '''
        Block tags have syntax like this:

        >> table
            >> tr
                >> td
                    foo
                >> td
                    bar

        FORM is just a shortcut.
        '''
        m = re.match('>> (.*)', line)
        markup = m.group(1)
        m = re.match('FORM (.*)', markup)
        if m:
            markup = 'form action="{%% url %s %%}" method="POST"' % m.group(1)
        start_tag = '<%s>' % markup
        end_tag = '</%s>' % markup.split()[0]
        indenter.push(prefix, start_tag, end_tag)

    def django_block(prefix, line, indenter):
        '''
        Enable code like this:

        %% extends 'base.html'
        %% load smartif

        %% block body
            %% for book in books
                {{ book }}

            %% if condition
                Display this
            %% elif condition
                Display that
            %% else
                %% include 'other.html' 
        '''
        m = re.match('%% (.*)', line)
        markup = m.group(1)
        tag = markup.split()[0]
        start_tag = '{%% %s %%}' % markup
        if tag in ['elif', 'else', 'include', 'extends', 'load']:
            indenter.insert(prefix, start_tag)
        else:
            end_tag = '{%% end%s %%}' % tag
            indenter.push(prefix, start_tag, end_tag)

    def fix_line(line):
        '''
        Fix up individual lines of HTML:

            List item one | b | li ; br
            Home LINK home.home
        
        LINK is just a django-specific shortcut.

        This is a bit crufty...there are some mini features
        that just allowed me to match some old markup without
        creating diffs.
        '''
        if line == '':
            return ''
        if line[-1] in [':', ',']:
            return fix_line(line[:-1]) + line[-1]
        if line.endswith('| ()'):
            line = line[:-len('| ()')]
            return '(%s)' % fix_line(line).rstrip()
        if line.endswith('; br'):
            line = line[:-len('; br')]
            return fix_line(line).rstrip() + '<br />'
        if line.endswith('; hr'):
            line = line[:-len('; hr')]
            return fix_line(line).rstrip() + '<hr />'
        m = re.match('(.*)\| (.*)', line)
        if m:
            content, markup = m.groups()
            return inline_html_tag(content, markup)
        m = re.match('(.*) LINK (.*)', line)
        if m:
            label, url = m.groups()
            return '<a href="{%% url %s %%}">%s</a>' % (url.rstrip(), label.rstrip())
            content, markup = m.groups()
            return inline_html_tag(content, markup)
        return line

    def inline_html_tag(content, markup):
        '''
        Enclose one HTML tag a time

            hello | b => <b>hello</b>
        
        HIDDEN is just a django-specific shortcut.

        / means write a singleton tag like <tag ... />

        NOCLOSE is legacy to avoid diffs...it writes the singleton tag
        without the /> at the end.
        '''
        content = fix_line(content.strip())
        markup = markup.strip()
        if markup.startswith('HIDDEN'):
            name = markup.split()[1]
            return '<input type="hidden" name="%s" value="{{ referral.id }}" />' % name
        if markup.endswith(' NOCLOSE'):
            markup = markup[:-len(' NOCLOSE')]
            start_tag = '<%s>' % markup
            end_tag = ''
        elif markup.endswith(' /'):
            start_tag = '<%s>' % markup
            end_tag = ''
        else:
            start_tag = '<%s>' % markup
            end_tag = '</%s>' % markup.split()[0]
        return start_tag + content + end_tag


    class Indenter:
        '''
        Example usage:

        indenter = Indenter()
        indenter.push('', 'Start', 'End')
        indenter.push('    ', 'Foo', '/Foo')
        indenter.add ('        ', 'bar')
        indenter.add ('    ', 'yo')
        print indenter.body()
        '''
        def __init__(self):
            self.stack = []
            self.lines = []
            self.adj = 0

        def push(self, prefix, start, end):
            self.add(prefix, start)
            self.stack.append((prefix, end))

        def dedent(self):
            self.adj += 4

        def end_dedent(self, prefix):
            self.pop(prefix)
            self.adj -= 4

        def add(self, prefix, line):
            if line:
                self.pop(prefix)
            self.insert(prefix, line)

        def insert(self, prefix, line):
            prefix = prefix[self.adj:]
            self.lines.append(prefix+line)

        def pop(self, prefix):
            while self.stack:
                start_prefix, end =  self.stack[-1]
                if len(prefix) <= len(start_prefix):
                    whitespace_lines = []
                    while self.lines and self.lines[-1] == '':
                        whitespace_lines.append(self.lines.pop())
                    self.insert(start_prefix, end)
                    self.lines += whitespace_lines
                    self.stack.pop()
                else:
                    return

        def body(self):
            self.pop('')
            return '\n'.join(self.lines)
                
    if __name__ == '__main__':
        publish('TEMPLATES')

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months 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, 7 months ago

Comments

Please login first before commenting.