📄 ezt.py
字号:
#!/usr/bin/env python"""ezt.py -- easy templatingezt templates are very similar to standard HTML files. But additionallythey contain directives sprinkled in between. With these directivesit is possible to generate the dynamic content from the ezt templates.These directives are enclosed in square brackets. If you are a C-programmer, you might be familar with the #ifdef directives of theC preprocessor 'cpp'. ezt provides a similar concept for HTML. Additionally EZT has a 'for' directive, which allows to iterate (repeat) certain subsections of the template according to sequence of data itemsprovided by the application.The HTML rendering is performed by the method generate() of the Templateclass. Building template instances can either be done using externalEZT files (convention: use the suffix .ezt for such files): >>> template = Template("../templates/log.ezt")or by calling the parse() method of a template instance directly with a EZT template string: >>> template = Template() >>> template.parse('''<html><head> ... <title>[title_string]</title></head> ... <body><h1>[title_string]</h1> ... [for a_sequence] <p>[a_sequence]</p> ... [end] <hr> ... The [person] is [if-any state]in[else]out[end]. ... </body> ... </html> ... ''')The application should build a dictionary 'data' and pass it togetherwith the output fileobject to the templates generate method: >>> data = {'title_string' : "A Dummy Page", ... 'a_sequence' : ['list item 1', 'list item 2', 'another element'], ... 'person': "doctor", ... 'state' : None } >>> import sys >>> template.generate(sys.stdout, data) <html><head> <title>A Dummy Page</title></head> <body><h1>A Dummy Page</h1> <p>list item 1</p> <p>list item 2</p> <p>another element</p> <hr> The doctor is out. </body> </html>Template syntax error reporting should be improved. Currently it is very sparse (template line numbers would be nice): >>> Template().parse("[if-any where] foo [else] bar [end unexpected args]") Traceback (innermost last): File "<stdin>", line 1, in ? File "ezt.py", line 220, in parse self.program = self._parse(text) File "ezt.py", line 275, in _parse raise ArgCountSyntaxError(str(args[1:])) ArgCountSyntaxError: ['unexpected', 'args'] >>> Template().parse("[if unmatched_end]foo[end]") Traceback (innermost last): File "<stdin>", line 1, in ? File "ezt.py", line 206, in parse self.program = self._parse(text) File "ezt.py", line 266, in _parse raise UnmatchedEndError() UnmatchedEndErrorDirectives========== Several directives allow the use of dotted qualified names refering to objects or attributes of objects contained in the data dictionary given to the .generate() method. Simple directives ----------------- [QUAL_NAME] This directive is simply replaced by the value of identifier from the data dictionary. QUAL_NAME might be a dotted qualified name refering to some instance attribute of objects contained in the dats dictionary. Numbers are converted to string though. [include "filename"] or [include QUAL_NAME] This directive is replaced by content of the named include file. Block directives ---------------- [for QUAL_NAME] ... [end] The text within the [for ...] directive and the corresponding [end] is repeated for each element in the sequence referred to by the qualified name in the for directive. Within the for block this identifiers now refers to the actual item indexed by this loop iteration. [if-any QUAL_NAME [QUAL_NAME2 ...]] ... [else] ... [end] Test if any QUAL_NAME value is not None or an empty string or list. The [else] clause is optional. CAUTION: Numeric values are converted to string, so if QUAL_NAME refers to a numeric value 0, the then-clause is substituted! [if-index INDEX_FROM_FOR odd] ... [else] ... [end] [if-index INDEX_FROM_FOR even] ... [else] ... [end] [if-index INDEX_FROM_FOR first] ... [else] ... [end] [if-index INDEX_FROM_FOR last] ... [else] ... [end] [if-index INDEX_FROM_FOR NUMBER] ... [else] ... [end] These five directives work similar to [if-any], but are only useful within a [for ...]-block (see above). The odd/even directives are for example useful to choose different background colors for adjacent rows in a table. Similar the first/last directives might be used to remove certain parts (for example "Diff to previous" doesn't make sense, if there is no previous). [is QUAL_NAME STRING] ... [else] ... [end] [is QUAL_NAME QUAL_NAME] ... [else] ... [end] The [is ...] directive is similar to the other conditional directives above. But it allows to compare two value references or a value reference with some constant string. """## Copyright (C) 2001-2002 Greg Stein. All Rights Reserved.## Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met:## * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.### This software is maintained by Greg and is available at:# http://viewcvs.sourceforge.net/# it is also used by the following projects:# http://edna.sourceforge.net/#import stringimport refrom types import StringType, IntType, FloatTypeimport os## This regular expression matches three alternatives:# expr: DIRECTIVE | BRACKET | COMMENT# DIRECTIVE: '[' ITEM (whitespace ITEM)* ']# ITEM: STRING | NAME# STRING: '"' (not-slash-or-dquote | '\' anychar)* '"'# NAME: (alphanum | '_' | '-' | '.')+# BRACKET: '[[]'# COMMENT: '[#' not-rbracket* ']'## When used with the split() method, the return value will be composed of# non-matching text and the two paren groups (DIRECTIVE and BRACKET). Since# the COMMENT matches are not placed into a group, they are considered a# "splitting" value and simply dropped.#_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.]+)'_re_parse = re.compile(r'\[(%s(?: +%s)*)\]|(\[\[\])|\[#[^\]]*\]' % (_item, _item))_re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.]+')# block commands and their argument counts_block_cmd_specs = { 'if-index':2, 'for':1, 'is':2 }_block_cmds = _block_cmd_specs.keys()# two regular expressions for compressing whitespace. the first is used to# compress any whitespace including a newline into a single newline. the# second regex is used to compress runs of whitespace into a single space._re_newline = re.compile('[ \t\r\f\v]*\n\\s*')_re_whitespace = re.compile(r'\s\s+')# this regex is used to substitute arguments into a value. we split the value,# replace the relevant pieces, and then put it all back together. splitting# will produce a list of: TEXT ( splitter TEXT )*. splitter will be '%' or# an integer._re_subst = re.compile('%(%|[0-9]+)')class Template: def __init__(self, fname=None, compress_whitespace=1): self.compress_whitespace = compress_whitespace if fname: self.parse_file(fname) def parse_file(self, fname): "fname -> a string object with pathname of file containg an EZT template." self.program = self._parse(_FileReader(fname)) def parse(self, text_or_reader): """Parse the template specified by text_or_reader. The argument should be a string containing the template, or it should specify a subclass of ezt.Reader which can read templates. """ if not isinstance(text_or_reader, Reader): # assume the argument is a plain text string text_or_reader = _TextReader(text_or_reader) self.program = self._parse(text_or_reader) def generate(self, fp, data): ctx = _context() ctx.data = data ctx.for_index = { } self._execute(self.program, fp, ctx) def _parse(self, reader, for_names=None, file_args=()): """text -> string object containing the HTML template. This is a private helper function doing the real work for method parse. It returns the parsed template as a 'program'. This program is a sequence made out of strings or (function, argument) 2-tuples. Note: comment directives [# ...] are automatically dropped by _re_parse. """ # parse the template program into: (TEXT DIRECTIVE BRACKET)* TEXT parts = _re_parse.split(reader.text) program = [ ] stack = [ ] if not for_names: for_names = [ ] for i in range(len(parts)): piece = parts[i] which = i % 3 # discriminate between: TEXT DIRECTIVE BRACKET if which == 0: # TEXT. append if non-empty. if piece: if self.compress_whitespace: piece = _re_whitespace.sub(' ', _re_newline.sub('\n', piece)) program.append(piece) elif which == 2: # BRACKET directive. append '[' if present. if piece: program.append('[') elif piece: # DIRECTIVE is present. args = _re_args.findall(piece) cmd = args[0] if cmd == 'else': if len(args) > 1: raise ArgCountSyntaxError(str(args[1:])) ### check: don't allow for 'for' cmd idx = stack[-1][1] true_section = program[idx:] del program[idx:] stack[-1][3] = true_section elif cmd == 'end': if len(args) > 1: raise ArgCountSyntaxError(str(args[1:])) # note: true-section may be None try: cmd, idx, args, true_section = stack.pop() except IndexError: raise UnmatchedEndError() else_section = program[idx:] func = getattr(self, '_cmd_' + re.sub('-', '_', cmd)) program[idx:] = [ (func, (args, true_section, else_section)) ] if cmd == 'for': for_names.pop()
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -