Package spade :: Module pyratemp
[hide private]
[frames] | no frames]

Module pyratemp

source code


Small, simple and powerful template-engine for python.

This is a template-engine for python, which is very simple, easy to use,
small, fast, powerful and pythonic.

See documentation for a list of features, template-syntax etc.

:Version:   0.1.4 (2008-12-21)
:Status:    beta

:Usage:
    see class 'Template' and examples below.

:Example:

    quickstart::
        >>> t = Template("hello @!name!@")
        >>> print t(name="marvin")
        hello marvin

    generic usage::
        >>> t = Template("output is in Unicode äöü€")
        >>> t                                           #doctest: +ELLIPSIS
        <...Template instance at 0x...>
        >>> t()
        u'output is in Unicode \xe4\xf6\xfc\u20ac'
        >>> unicode(t)
        u'output is in Unicode \xe4\xf6\xfc\u20ac'

    with data::
        >>> t = Template("hello @!name!@", data={"name":"world"})
        >>> t()
        u'hello world'
        >>> t(name="worlds")
        u'hello worlds'

        # >>> t(note="data must be Unicode or ASCII", name=u"ä")
        # u'hello \xe4\xf6\xe4\u20ac'

    python-expressions::
        >>> Template('formatted: @! "%10.7f" % value !@')(value=3.141592653)
        u'formatted:  3.1415927'
        >>> Template("hello --@!name.upper().center(20)!@--")(name="world")
        u'hello --       WORLD        --'
        >>> Template("calculate @!var*5+7!@")(var=7)
        u'calculate 42'

    escaping::
        >>> t = Template("hello escaped @!name!@")
        >>> t(name='''<>&'" ''')
        u'hello escaped &lt;&gt;&amp;&#39;&quot; '
        >>> t = Template("hello unescaped $!name!$")
        >>> t(name='''<>&'" ''')
        u'hello unescaped <>&\'" '
    
    result-encoding::
        # encode the unicode-object to your encoding with encode()
        >>> result = Template("hello äöü€")()
        >>> result
        u'hello \xe4\xf6\xfc\u20ac'
        >>> result.encode("utf-8")
        'hello \xc3\xa4\xc3\xb6\xc3\xbc\xe2\x82\xac'
        >>> result.encode("ascii")
        Traceback (most recent call last):
          ...
        UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-9: ordinal not in range(128)
        >>> result.encode("ascii", 'xmlcharrefreplace')
        'hello &#228;&#246;&#252;&#8364;'

    default-values::
        # non-existing variables raise an error
        >>> Template('hi @!optional!@')()
        Traceback (most recent call last):
          ...
        TemplateRenderError: Cannot eval expression 'optional' (NameError: name 'optional' is not defined)

        >>> t = Template('hi @!default("optional","anyone")!@')
        >>> t()
        u'hi anyone'
        >>> t(optional=None)
        u'hi anyone'
        >>> t(optional="there")
        u'hi there'

        # also in blocks
        >>> t = Template('<!--(if default("optional",False))-->yes<!--(else)-->no<!--(end)-->')
        >>> t()
        u'no'
        >>> t(optional=23)
        u'yes'
        
        # the 1st parameter can be any eval-expression
        >>> t = Template('@!default("5*var1+var2","missing variable")!@')
        >>> t(var1=10)
        u'missing variable'
        >>> t(var1=10, var2=2)
        u'52'

        # but make sure to put the expression in quotation marks, otherwise:
        >>> Template('@!default(optional,"fallback")!@')()
        Traceback (most recent call last):
          ...
        TemplateRenderError: Cannot eval expression 'default(optional,"fallback")' (NameError: name 'optional' is not defined)

    exists:
        >>> t = Template('<!--(if exists("foo"))-->YES<!--(else)-->NO<!--(end)-->')
        >>> t()
        u'NO'
        >>> t(foo=1)
        u'YES'
        >>> t(foo=None)       # note this difference to 'default()'
        u'YES'

:Note:

:Author:    Roland Koebler (rk at simple-is-better dot org)
:Copyright: 2007-2008 by Roland Koebler
:License:   MIT/X11-like, see __license__

:TODO:
    - enhance/extend escape()
    - speedup:
        - ? load/save parsed (marshal+check python-version)
        - ? psyco
        - ? escape -> C ?
        - ? compiler, (eval("\w+") -> data[..])

    - extensions:
        - ? set/define variables / capture output ?
          (i.e. <!--(set var)-->[1,2,3]<!--(end)-->)
        - ? filter ? (function over block)


Version: 0.1.4

Author: Roland Koebler <rk at simple-is-better dot org>

License: Copyright (c) 2007-2008 by Roland Koebler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Classes [hide private]
  TemplateException
Base class for template-exceptions.
  TemplateParseError
Template parsing failed.
  TemplateSyntaxError
Template syntax-error.
  TemplateIncludeError
Template 'include' failed.
  TemplateRenderError
Template rendering failed.
  TemplateBase
Basic template-class.
  Template
Template-User-Interface.
  StringLoader
Load a template from a string.
  FileLoader
Load template from a file.
  Parser
Parse a template into a parse-tree.
  PseudoSandbox
A pseudo-eval-sandbox.
  TemplateEval
PseudoSandbox with some additional functions, which are useful in the template.
  _dontescape
Unicode-string which should not be escaped.
  Renderer
Render a template-parse-tree.
Functions [hide private]
 
srow(string, i)
Get row/lineno of string[i].
source code
 
scol(string, i)
Get column of string[i].
source code
 
sindex(string, row, col)
Get string-index of the character at row/lineno,col.
source code
 
dictkeyclean(d)
Convert all keys of d to strings.
source code
 
escape(s, format=0)
Replace special characters by their escape sequence.
source code
 
dummy(*args, **kwargs)
Dummy function, doing nothing.
source code
 
dummy_raise(exception, value)
Dummy-function-creater.
source code
 
_doctest()
doctest this module.
source code
Variables [hide private]
  ESCAPE_SUPPORTED = {'HTML': 0, 'LATEX': 1, 'NONE': None}
  HTML = 0
  LATEX = 1
  __package__ = 'spade'
Function Details [hide private]

srow(string, i)

source code 

Get row/lineno of string[i].

:Returns: row, starting at 1 :Note: This works for text-strings with '\n' or '\r\n'.

scol(string, i)

source code 

Get column of string[i].

:Returns: column, starting at 1 (but may be <1 if i<0) :Note: This works for text-strings with '\n' or '\r\n'.

sindex(string, row, col)

source code 

Get string-index of the character at row/lineno,col.

:Parameters: row,col, starting at 1. :Returns: i, starting at 0. (but may be <1 if row/col<0) :Note: This works for text-strings with '\n' or '\r\n'.

escape(s, format=0)

source code 
Replace special characters by their escape sequence.

:Parameters:
    - `s`:      string or unicode-string to escape
    - `format`:
        - None:  nothing is replaced
        - HTML:  replace &<>'" by &...;
        - LATEX: replace #$%&_{}"\ (TODO! - this is very incomplete!)
:Returns:
    the escaped string in unicode
:TODO:  complete LaTeX-escaping

dummy_raise(exception, value)

source code 

Dummy-function-creater.

:Returns: dummy function, raising exception(value)