Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 060db3995a
Fetching contributors…

Cannot retrieve contributors at this time

file 173 lines (136 sloc) 5.012 kb
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
"""
Interface to various templating engines.
"""
import os.path

__all__ = [
    "render_cheetah", "render_genshi", "render_mako",
    "cache",
]

class render_cheetah:
    """Rendering interface to Cheetah Templates.

Example:

render = render_cheetah('templates')
render.hello(name="cheetah")
"""
    def __init__(self, path):
        # give error if Chetah is not installed
        from Cheetah.Template import Template
        self.path = path

    def __getattr__(self, name):
        from Cheetah.Template import Template
        path = os.path.join(self.path, name + ".html")
        
        def template(**kw):
            t = Template(file=path, searchList=[kw])
            return t.respond()

        return template
    
class render_genshi:
    """Rendering interface genshi templates.
Example:

for xml/html templates.

render = render_genshi(['templates/'])
render.hello(name='genshi')

For text templates:

render = render_genshi(['templates/'], type='text')
render.hello(name='genshi')
"""

    def __init__(self, *a, **kwargs):
        from genshi.template import TemplateLoader

        self._type = kwargs.pop('type', None)
        self._loader = TemplateLoader(*a, **kwargs)

    def __getattr__(self, name):
        # Assuming all templates are html
        path = name + ".html"

        if self._type == "text":
            from genshi.template import TextTemplate
            cls = TextTemplate
            type = "text"
        else:
            cls = None
            type = None

        t = self._loader.load(path, cls=cls)
        def template(**kw):
            stream = t.generate(**kw)
            if type:
                return stream.render(type)
            else:
                return stream.render()
        return template

class render_jinja:
    """Rendering interface to Jinja2 Templates
Example:

render= render_jinja('templates')
render.hello(name='jinja2')
"""
    def __init__(self, *a, **kwargs):
        extensions = kwargs.pop('extensions', [])
        globals = kwargs.pop('globals', {})

        from jinja2 import Environment,FileSystemLoader
        self._lookup = Environment(loader=FileSystemLoader(*a, **kwargs), extensions=extensions)
        self._lookup.globals.update(globals)
        
    def __getattr__(self, name):
        # Assuming all templates end with .html
        path = name + '.html'
        t = self._lookup.get_template(path)
        return t.render
        
class render_mako:
    """Rendering interface to Mako Templates.

Example:

render = render_mako(directories=['templates'])
render.hello(name="mako")
"""
    def __init__(self, *a, **kwargs):
        from mako.lookup import TemplateLookup
        self._lookup = TemplateLookup(*a, **kwargs)

    def __getattr__(self, name):
        # Assuming all templates are html
        path = name + ".html"
        t = self._lookup.get_template(path)
        return t.render

class render_tempita:
    """Rendering interface to Tempita templates.

Example:

render = render_tempita(['templates'])
render.hello(name='tempita')
"""

    extensions = {
        '.html': ('HTMLTemplate', 'text/html; charset=utf-8'),
        '.xhtml': ('HTMLTemplate', 'application/xhtml+xml; charset=utf-8'),
        '.txt': ('Template', 'text/plain'),
    }

    def __init__(self, directories):
        import tempita
        self.directories = directories

    def _get_template(self, name, from_template=None):
        import tempita
        for directory in self.directories:
            for extension in self.extensions:
                filename = os.path.join(directory, name + extension)
                if os.path.exists(filename):
                    if not from_template:
                        from_template = getattr(tempita, self.extensions[extension][0])
                    template = from_template.from_filename(filename, get_template=self._get_template)
                    template.content_type = self.extensions[extension][1]
                    return template

    def __getattr__(self, name):
        template = self._get_template(name)
        if not template:
            raise AttributeError('Template "%s" not found.' % name)
        def render(*args, **kwargs):
            import web
            if 'headers' in web.ctx and template.content_type:
                web.header('Content-Type', template.content_type, unique=True)
            return template.substitute(*args, **kwargs)
        return render

class cache:
    """Cache for any rendering interface.
Example:

render = cache(render_cheetah("templates/"))
render.hello(name='cache')
"""
    def __init__(self, render):
        self._render = render
        self._cache = {}

    def __getattr__(self, name):
        if name not in self._cache:
            self._cache[name] = getattr(self._render, name)
        return self._cache[name]
Something went wrong with that request. Please try again.