Package PyFoam :: Package ThirdParty :: Module pyratemp
[hide private]
[frames] | no frames]

Module pyratemp

source code


Small, simple and powerful template-engine for python.

A template-engine for python, which is very simple, easy to use, small,
fast, powerful, modular, extensible, well documented and pythonic.

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

:Version:   0.2.0

: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'

    escaping::
        >>> t = Template("hello escaped: @!name!@, unescaped: $!name!$")
        >>> t(name='''<>&'"''')
        u'hello escaped: &lt;&gt;&amp;&#39;&quot;, unescaped: <>&\'"'

    result-encoding::
        # encode the unicode-object to your encoding with encode()
        >>> t = Template("hello äöü€")
        >>> result = t()
        >>> 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;'

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

    blocks (if/for/macros/...)::
        >>> t = Template("<!--(if foo == 1)-->bar<!--(elif foo == 2)-->baz<!--(else)-->unknown(@!foo!@)<!--(end)-->")
        >>> t(foo=2)
        u'baz'
        >>> t(foo=5)
        u'unknown(5)'

        >>> t = Template("<!--(for i in mylist)-->@!i!@ <!--(else)-->(empty)<!--(end)-->")
        >>> t(mylist=[])
        u'(empty)'
        >>> t(mylist=[1,2,3])
        u'1 2 3 '

        >>> t = Template("<!--(for i,elem in enumerate(mylist))--> - @!i!@: @!elem!@<!--(end)-->")
        >>> t(mylist=["a","b","c"])
        u' - 0: a - 1: b - 2: c'

        >>> t = Template('<!--(macro greetings)-->hello <strong>@!name!@</strong><!--(end)-->  @!greetings(name=user)!@')
        >>> t(user="monty")
        u'  hello <strong>monty</strong>'

    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'

    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'

        # 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'

        # also in blocks
        >>> t = Template('<!--(if default("opt1+opt2",0) > 0)-->yes<!--(else)-->no<!--(end)-->')
        >>> t()
        u'no'
        >>> t(opt1=23, opt2=42)
        u'yes'

        >>> t = Template('<!--(for i in default("optional_list",[]))-->@!i!@<!--(end)-->')
        >>> t()
        u''
        >>> t(optional_list=[1,2,3])
        u'123'


        # 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)

    setvar::
        >>> t = Template('$!setvar("i", "i+1")!$@!i!@')
        >>> t(i=6)
        u'7'

        >>> t = Template('''<!--(if isinstance(s, (list,tuple)))-->$!setvar("s", '"\\\\n".join(s)')!$<!--(end)-->@!s!@''')
        >>> t(isinstance=isinstance, s="123")
        u'123'
        >>> t(isinstance=isinstance, s=["123", "456"])
        u'123\n456'

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


Version: 0.2.0

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

License: Copyright (c) Roland Koebler, 2007-2010 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]
  EvalPseudoSandbox
An eval-pseudo-sandbox.
  LoaderFile
Load template from a file.
  LoaderString
Load template from a string/unicode.
  Parser
Parse a template into a parse-tree.
  Renderer
Render a template-parse-tree.
  Template
Template-User-Interface.
  TemplateBase
Basic template-class.
  TemplateException
Base class for template-exceptions.
  TemplateIncludeError
Template 'include' failed.
  TemplateParseError
Template parsing failed.
  TemplateRenderError
Template rendering failed.
  TemplateSyntaxError
Template syntax-error.
  _dontescape
Unicode-string which should not be escaped.
Functions [hide private]
 
_doctest()
doctest this module.
source code
 
dictkeyclean(d)
Convert all keys of the dict `d` to strings.
source code
 
dummy(*args, **kwargs)
Dummy function, doing nothing.
source code
 
dummy_raise(exception, value)
Create an exception-raising dummy function.
source code
 
escape(s, format=1)
Replace special characters by their escape sequence.
source code
 
scol(string, i)
Get column number of ``string[i]`` in `string`.
source code
 
sindex(string, row, col)
Get index of the character at `row`/`col` in `string`.
source code
 
srow(string, i)
Get line numer of ``string[i]`` in `string`.
source code
 
toUniCode(s) source code
Variables [hide private]
  ESCAPE_SUPPORTED = {'HTML': 1, 'LATEX': 2, 'NONE': None}
  HTML = 1
  LATEX = 2
  NONE = 0
  PY3 = False
  __package__ = 'PyFoam.ThirdParty'
  string_types = (<type 'basestring'>)

Imports: __builtin__, iteritems, os, re, sys, text_type, toUni


Function Details [hide private]

dummy_raise(exception, value)

source code 

Create an exception-raising dummy function.

:Returns: dummy function, raising ``exception(value)``

escape(s, format=1)

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
:Exceptions:
    - `ValueError`: if `format` is invalid.

:TODO:  complete LaTeX-escaping, optimize speed

scol(string, i)

source code 

Get column number of ``string[i]`` in `string`.

: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 index of the character at `row`/`col` in `string`.

:Parameters:

  • `row`: row number, starting at 1.
  • `col`: column number, 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'.

srow(string, i)

source code 

Get line numer of ``string[i]`` in `string`.

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