Welcome, guest | Sign In | My Account | Store | Cart

This module is the Template Macro module. It preprocesses a web template in which variables and blocks are contained. This package plays an important role as an explicit boundary between web template designing and script implementation.

Python, 510 lines
  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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
#!/usr/bin/env python
#-*- coding: utf-8 -*-

'''
This module is the B{Template Macro} module. It preprocesses a web 
template in which variables and blocks are contained. This package 
plays an important role as an explicit boundary between web template 
designing and script implementation.

@note: A block can be defined with block comment:
C{<!-- block }M{q}C{ start -->}
M{c}
C{<!-- block }M{q}C{ end -->},
where M{q} is the block name and M{c} is the content of this block.

@note: It should be noted that each subblock symbol is necessary to 
differ from its superblock's name. This is owing to the block pattern.

@author: Prachya Boonkwan
@organization: NAI{i}ST Laboratory, Kasetsart University, Thailand
@copyright: October 23, 2003
'''

########################################

import copy
import re
import string

########################################

class Template:
    '''
    Web template representation. As soon as the template instance is 
    constructed, the content is automatically analyzed and the symbol 
    table is afterward created.

    @ivar path: Path to web template file.
    @type path: str
    @ivar content: Textual content of web template.
    @type content: str
    @ivar symtab: Symbol table of web template
    @type symtab: dict

    @cvar blkpat: Block declaration pattern (regular expression). It
    should be noted that this pattern does I{not} greedily match the
    block body.
    '''

    blkpat = re.compile(
        r'\s*<!---*\s*block\s*(?P<blkname>\w+?)\s*(start|begin)\s*-*-->'
        r'(?P<blkbody>\s*.*?)'
        r'\s*<!---*\s*block\s*(?P=blkname)\s*end\s*-*-->',
        re.DOTALL
    )

    def __init__(self, path = None, content = None, symtab = None):
        '''
        Construct a web template representation.

        @param path: Path to web template file.
        @type path: str
        @param content: Textual content of web template
        @type content: str
        @param symtab: Symbol table of web template
        @type symtab: dict
        
        @note: It is recommended to specify only the path of the 
        template.
        '''

        if symtab is None: symtab = {}

        self.path = path
        self.content = content
        self.symtab = symtab

        if self.content is None or len(self.symtab) == 0:
            if self.path is not None:
                self.load()
            self.content = self.analyze(self.content)

    def __copy__(self):
        '''
        Copy a web template representation.
        '''

        return Template(
            self.path, self.content, copy.copy(self.symtab)
        )

    def load(self):
        '''
        Load the content of the template from the specified path.
        '''

        fhdl = open(self.path)
        self.content = fhdl.read()
        fhdl.close()

    def analyze(self, text, blkpath = None):
        '''
        Analyze the text to establish blocks.

        @param text: Text to be analyzed.
        @type text: str
        @param blkpath: Block path to the text.
        @type blkpath: list

        @return: Content which blocks are replaced with symbols.
        @rtype: str

        @raise TemplateError: If symbol reassignment occurs.
        '''

        if blkpath is None: blkpath = []

        result = text

        while True:
            matobj = Template.blkpat.search(result)
            if matobj is None: break
            blkname = matobj.group('blkname')
            symbol = string.join(blkpath + [blkname], '.')
            blkbody = matobj.group('blkbody')
            (result, _) = Template.blkpat.subn(
                '[[:%s:]]' % symbol, result, 1
            )
            value = self.analyze(blkbody, blkpath + [blkname])

            if symbol not in self.symtab.keys():
                self.symtab[symbol] = value
            else:
                raise TemplateError, \
                'Reassigning the same symbol (%s).' % symbol

        return result

    def __getitem__(self, symbol):
        '''
        Get the value of the symbol.

        @param symbol: Symbol name.
        @type symbol: str

        @return: Value of the symbol.
        @rtype: str
        '''

        return self.symtab[symbol]

    def repr(self):
        '''
        Represent this template with a string representation.

        @return: String C{Template(path = }M{p}C{, content = }M{c}
        C{, symtab = }M{s}C{)}, where M{p} is the path, M{c} is the 
        content of that template, and M{s} is the symbol table.
        @rtype: str
        '''

        return 'Template(path = %r, content = %r, symtab = %r)' % (
            self.path, self.content, self.symtab
        )

    __repr__ = __str__ = repr

########################################

class TemplateError(Exception):
    '''
    Error occurring in the class Template.
    '''

    pass

########################################

class PageMacro:
    '''
    Page Macro Expander. It enables users to define symbols in order 
    to be expanded to templates further. Moreover, also enables users 
    to expand consecutively blocks in templates.

    @ivar symtab: Symbol table.
    @type symtab: dict

    @cvar KEEPMODE: Mode of keeping all undefined symbols.
    @type KEEPMODE: int
    @cvar DELMODE: Mode of deleting all undefined symbols.
    @type DELMODE: int

    @cvar varpat: Symbol pattern.
    @cvar unkpat: Unknown symbol pattern.
    '''

    KEEPMODE = 0
    DELMODE = 1

    varpat = re.compile(r'\[\[:(?P<symname>(\w+\.)*\w+?):\]\]')
    unkpat = re.compile(r'\[\[::(?P<synname>(\w+\.)*\w+?)::\]\]')

    def __init__(self, mainsym, unkmthd = None, symtab = None):
        '''
        Construct a page macro expander.

        @param mainsym: Main symbol to be displayed.
        @type mainsym: str
        @param unkmthd: Resolution method of undefined symbols
        (C{PageMacro.KEEPMODE} or C{PageMacro.DELMODE}).
        @type unkmthd: int
        @param symtab: Symbol table.
        @type symtab: dict
        '''

        if unkmthd is None: unkmthd = PageMacro.KEEPMODE
        if symtab is None: symtab = {}

        self.mainsym = mainsym
        self.unkmthd = unkmthd
        self.symtab = symtab

    def __copy__(self):
        '''
        Copy a page macro expander.
        '''

        return PageMacro(
            self.mainsym, self.unkmthd, copy.copy(self.symtab)
        )

    def repr(self):
        '''
        Represent a page macro expander with a string representation.

        @return: String C{PageMacro(mainsym = }M{q}C{, unkmthd = }M{m}
        C{, symtab = }M{s}C{)}, where M{q} is the main symbol, M{m} is 
        the resolution method of unknown or undefined symbols and M{s} 
        is the symbol table.
        @rtype: str
        '''

        return 'PageMacro(mainsym = %s, unkmthd = %d, symtab = %r)' % (
            self.mainsym, self.unkmthd, self.symtab
        )

    __repr__ = repr

    def __getitem__(self, symbol):
        '''
        Get the value of a symbol.

        @param symbol: Symbol name.
        @type symbol: str

        @return: Value of the symbol.
        @rtype: Template
        '''

        return self.symtab[symbol]

    def __setitem__(self, symbol, value):
        '''
        Set the value of a symbol.

        @param symbol: Symbol name.
        @type symbol: str
        @param value: Value of the symbol.
        @type value: str or Template

        @note: The parameter C{value} of a symbol can be a string or a
        template. If it is a string, it will be considered as the
        content of the template and it will be wrapped with Template
        class. On the contrary, if it is a template, it will be
        directly assigned to the symbol.

        @note: If users would like to assign to a symbol with the path
        to a template file, please use C{pm[}M{s}C{] = 
        Template(path = }M{p}C{)}, where C{pm} is a C{PageMacro} 
        instance, M{s} is a symbol name, and M{p} is a path to 
        template. Users can alternatively use the method C{load} for
        ease of use.

        @note: If users would like to assign directly to a symbol with
        the template content, please use C{pm[}M{s}C{] = }M{c}, where 
        C{pm} is a C{PageMacro} instance and M{c} is a content of
        template.
        '''

        if isinstance(value, Template):
            self.symtab[symbol] = value
        elif type(value) is str:
            self.symtab[symbol] = Template(content = value)

    def load(self, symbol, filename):
        '''
        Load a template file to a symbol.

        @param symbol: Symbol name.
        @type symbol: str
        @param filename: Template path.
        @type filename: str
        '''

        self[symbol] = Template(path = filename)

    def resolve(self, symbol):
        '''
        Resolve the specified symbol to absolute value.

        @param symbol: Symbol name.
        @type symbol: str

        @return: Absolute value of the symbol.
        @rtype: str
        '''

        if symbol not in self.symtab:
            return '[[::%s::]]' % symbol

        result = self.symtab[symbol].content

        while True:
            matobj = PageMacro.varpat.search(result)
            if matobj is None: break
            symname = matobj.group('symname')
            if symname in self.symtab:
                (result, _) = PageMacro.varpat.subn(
                    self.resolve(symname), result, 1
                )
            else:
                (result, _) = PageMacro.varpat.subn(
                    '[[::%s::]]' % symname, result, 1
                )

        return self.handle_unk(result)

    def handle_unk(self, text):
        '''
        Handle unknown symbols in the text.

        @param text: Text.
        @type text: str

        @return: Unknown-handled text.
        @rtype: str
        '''

        result = text

        while True:
            matobj = PageMacro.unkpat.search(result)
            if matobj is None: break
            if self.unkmthd == PageMacro.KEEPMODE:
                result = PageMacro.unkpat.sub(
                    '[[:\g<synname>:]]', result
                )
            elif self.unkmthd == PageMacro.DELMODE:
                result = PageMacro.unkpat.sub('', result)

        return result

    def envision(self, tempsym, blocksym, symdict):
        '''
        Resolve a block in a template with a symbol dictionary.

        @param tempsym: Template symbol.
        @type tempsym: str
        @param blocksym: Block symbol in the template.
        @type blocksym: str
        @param symdict: Symbol dictionary.
        @type symdict: dict

        @raise PageMacroError: If unknown switch is to be resolved.
        '''

        self.expand(tempsym, blocksym, [symdict])

    def expand(self, tempsym, blocksym, iterable):
        '''
        Expand consecutively a block in a template with an iterable.

        @param tempsym: Template symbol.
        @type tempsym: str
        @param blocksym: Block symbol in the template.
        @type blocksym: str
        @param iterable: Iterable list of dictionaries whose keys and
        values resemble correspondences among symbols and their 
        values. A value in the dictionary can be a list or an iterable
        to expand recursively the block. In this case, the key of such
        value is necessary to specify explicitly block hierarchy.
        @type iterable: list or iter

        @raise PageMacroError: If unknown block is to be resolved.
        '''

        if (
            tempsym not in self.symtab
        ):
            raise PageMacroError, \
            'Unknown template (%s) cannot be resolved.' % tempsym
            
        if (
            blocksym not in self.symtab[tempsym].symtab
        ):
            raise PageMacroError, \
            'Unknown block (%s) cannot be resolved.' % blocksym

        result = []

        for symdict in iterable:
            content = self.symtab[tempsym][blocksym]

            while True:
                matobj = PageMacro.varpat.search(content)
                if matobj is None: break
                symname = matobj.group('symname')
                
                if symname in symdict:
                    if type(symdict[symname]) is str:
                        self[symname] = symdict[symname]
                    elif type(symdict[symname]) in [list, iter]:
                        self.expand(tempsym, symname, symdict[symname])
                    elif type(symdict[symname]) is dict:
                        self.expand(
                            tempsym, symname, [symdict[symname]]
                        )

                (content, _) = PageMacro.varpat.subn(
                    self.resolve(symname), content, 1
                )

            result.append(content)

        self[blocksym] = string.join(result, '')

    def str(self):
        '''
        Represent a page macro expander with the expanded value of the 
        main symbol.

        @return: Expanded value.
        @rtype: str
        '''

        return self.resolve(self.mainsym)

    __str__ = str

########################################

class PageMacroError(Exception):
    '''
    Error occurring in the class PageMacro.
    '''

    pass

########################################

def demo():
    '''
    Demonstrate this module.
    '''
    
    input = '''
<html>
    This page was written by <b>[[:author:]]</b>.
    <!-- block TableBlock start -->
    <table>
        <th>
            <td>[[:h1:]]</td>
            <td>[[:h2:]]</td>
            <td>[[:h3:]]</td>
        </th>
        <!-- block RowBlock start -->
        <tr>
            <td>[[:c1:]]</td>
            <td>[[:c2:]]</td>
            <td>[[:c3:]]</td>
        </tr>
        <!-- block RowBlock end -->
    </table>
    <!-- block TableBlock end -->
</html>
    '''

    pm = PageMacro('Content', PageMacro.DELMODE)
    pm['Content'] = input
    pm['author'] = 'Prachya Boonkwan'
    pm.expand('Content', 'TableBlock', [
        {
            'h1': 'Country', 'h2': 'President', 'h3': 'Population',
            'TableBlock.RowBlock': [
                {'c1': 'USA', 'c2': 'Bush', 'c3': '200m'},
                {'c1': 'PRC', 'c2': 'Jintao', 'c3': '1,200m'}
            ]
        },
        {
            'h1': 'Class', 'h2': 'Instructor', 'h3': 'Student No.',
            'TableBlock.RowBlock': [
                {'c1': 'AI', 'c2': 'AK', 'c3': '60'},
                {'c1': 'NLP', 'c2': 'AK', 'c3': '50'}
            ]
        }
    ])
    print pm

if __name__ == '__main__':
    demo()

This program is motivated by PHP Template macro of PHPLIB. The innovation is that blocks can be expanded consecutively be a list of nested dictionaries of variables and their values.

1 comment

Prachya Boonkwan (author) 20 years, 5 months ago  # | flag

Documentation in the source code. In order to clarify all comments in the source code, kindly uses epydoc (http://epydoc.sourceforge.net) to generate a documentation.