How to use the genshi.template.TemplateLoader function in Genshi

To help you get started, we’ve selected a few Genshi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github apache / bloodhound / trac / trac / web / chrome.py View on Github external
def load_template(self, filename, method=None):
        """Retrieve a Template and optionally preset the template data.

        Also, if the optional `method` argument is set to `'text'`, a
        `NewTextTemplate` instance will be created instead of a
        `MarkupTemplate`.
        """
        if not self.templates:
            self.templates = TemplateLoader(
                self.get_all_templates_dirs(), auto_reload=self.auto_reload,
                max_cache_size=self.genshi_cache_size,
                default_encoding="utf-8",
                variable_lookup='lenient', callback=lambda template:
                Translator(translation.get_translations()).setup(template))

        if method == 'text':
            cls = NewTextTemplate
        else:
            cls = MarkupTemplate

        return self.templates.load(filename, cls=cls)
github nandoflorestan / bag / bag / web / pyramid / genshi.py View on Github external
if domain:
            from genshi.filters import Translator
            from pyramid.i18n import get_localizer
            from pyramid.threadlocal import get_current_request

            def translate(text):
                return get_localizer(get_current_request()) \
                    .translate(text, domain=domain)

            def callback(template):
                Translator(translate).setup(template)
        else:
            callback = None

        from genshi.template import TemplateLoader
        self.loader = TemplateLoader(
            paths, callback=callback,
            auto_reload=asbool(settings.get('pyramid.reload_templates')),
            max_cache_size=int(settings.get('genshi.max_cache_size', 100)))
        self.strip_whitespace = settings.get('genshi.strip_whitespace', True)
        self.doctype = settings.get('genshi.doctype', 'html5')
        self.method = settings.get('genshi.method', 'xhtml')
github XCSoar / XCSoar / mapgen / lib / xcsoar / mapgen / view.py View on Github external
import os
import cherrypy
from genshi.core import Stream
from genshi.output import encode, get_serializer
from genshi.template import Context, TemplateLoader

loader = TemplateLoader(
    os.path.join(os.path.dirname(__file__), 'views'),
    auto_reload=True
)

def output(filename, method='html', encoding='utf-8', **options):
    """Decorator for exposed methods to specify what template they should use
    for rendering, and which serialization method and options should be
    applied.
    """
    def decorate(func):
        def wrapper(*args, **kwargs):
            cherrypy.thread_data.template = loader.load(filename)
            opt = options.copy()
            if method == 'html':
                opt.setdefault('doctype', 'html')
            serializer = get_serializer(method, **opt)
github apache / bloodhound / trac / trac / web / main.py View on Github external
env = open_environment(env_path,
                                       use_cache=not environ['wsgi.run_once'])
                proj = {
                    'env': env,
                    'name': env.project_name,
                    'description': env.project_description,
                    'href': href(env_name)
                }
            except Exception, e:
                proj = {'name': env_name, 'description': to_unicode(e)}
            projects.append(proj)
        projects.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))

        data['projects'] = projects

        loader = TemplateLoader(loadpaths, variable_lookup='lenient',
                                default_encoding='utf-8')
        tmpl = loader.load(template)
        stream = tmpl.generate(**data)
        if template.endswith('.xml'):
            output = stream.render('xml')
            req.send(output, 'text/xml')
        else:
            output = stream.render('xhtml', doctype=DocType.XHTML_STRICT,
                                   encoding='utf-8')
            req.send(output, 'text/html')

    except RequestDone:
        pass
github phpmyadmin / website / render.py View on Github external
'awards': data.awards.AWARDS,
            'generated': helper.date.DateTime.utcnow(),
            'themecssversions': data.themes.CSSVERSIONS,
            'sfservers': data.sf.SERVERS,
            'current_year': datetime.datetime.now().year,
        }
        self.loader = TemplateLoader([TEMPLATES])
        self.cssloader = TemplateLoader(
            [CSS],
            default_class=NewTextTemplate
        )
        self.staticloader = TemplateLoader(
            [STATIC],
            default_class=NewTextTemplate
        )
        self.jsloader = TemplateLoader(
            [JS],
            default_class=NewTextTemplate
        )
        self.feeds = helper.cache.FeedCache()
        self.xmls = helper.cache.XMLCache()
        self.urls = helper.cache.URLCache()

        # Load Twitter settings
        self.twitter = None
        if TWITTER:
            config = ConfigParser.RawConfigParser()
            config.read(os.path.expanduser('~/.pmaweb'))
            try:
                consumer_key = config.get('twitter', 'consumer_key')
                consumer_secret = config.get('twitter', 'consumer_secret')
                token_key = config.get('twitter', 'token_key')
github pecan / pecan / pecan / templating.py View on Github external
def __init__(self, path, extra_vars):
            self.loader = TemplateLoader([path], auto_reload=True)
            self.extra_vars = extra_vars
github dag / flask-genshi / flaskext / genshi.py View on Github external
def template_loader(self):
        """A :class:`genshi.template.TemplateLoader` that loads templates
        from the same places as Flask.

        """
        path = loader.directory(os.path.join(self.app.root_path, 'templates'))
        module_paths = {}
        modules = getattr(self.app, 'modules', {})
        for name, module in modules.iteritems():
            module_path = os.path.join(module.root_path, 'templates')
            if os.path.isdir(module_path):
                module_paths[name] = loader.directory(module_path)
        return TemplateLoader([path, loader.prefixed(**module_paths)],
                              auto_reload=self.app.debug,
                              callback=self.callback)
github pallets / jinja / examples / rwbench / rwbench.py View on Github external
from datetime import datetime
from timeit import Timer
from jinja2 import Environment, FileSystemLoader
from jinja2.utils import generate_lorem_ipsum
from mako.lookup import TemplateLookup
from genshi.template import TemplateLoader as GenshiTemplateLoader


def dateformat(x):
    return x.strftime('%Y-%m-%d')


jinja_env = Environment(loader=FileSystemLoader(join(ROOT, 'jinja')))
jinja_env.filters['dateformat'] = dateformat
mako_lookup = TemplateLookup(directories=[join(ROOT, 'mako')])
genshi_loader = GenshiTemplateLoader([join(ROOT, 'genshi')])

class Article(object):

    def __init__(self, id):
        self.id = id
        self.href = '/article/%d' % self.id
        self.title = generate_lorem_ipsum(1, False, 5, 10)
        self.user = choice(users)
        self.body = generate_lorem_ipsum()
        self.pub_date = datetime.utcfromtimestamp(randrange(10 ** 9, 2 * 10 ** 9))
        self.published = True


class User(object):

    def __init__(self, username):
github JshWright / vboxweb / content.py View on Github external
#
# 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.
#
# ***** END LICENSE BLOCK *****

import os, sys, traceback, cherrypy, pickle
from genshi.template import TemplateLoader
from genshi.filters import HTMLFormFiller

loader = TemplateLoader(
    os.path.join(os.path.dirname(__file__), 'templates'),
    auto_reload=True
)

VM_STATES = (None, 'Powered Off', 'Saved', 'Aborted', 'Running', 'Paused',
                'Stuck', 'Starting', 'Stopping', 'Saving', 'Restoring',
                'Discarding', 'Setting Up')

class Root:

    def __init__(self, mgr, vbox):
        self.mgr = mgr
        self.vbox = vbox

    @cherrypy.expose
    def index(self):
github mullender / python-ntlm / sample_server / controller.py View on Github external
#!/usr/bin/env python

import operator, os, pickle, sys
import cherrypy
import NTLMAuth
from ntlm.HTTPServerAuthHandler import HTTPServerAuthHandler
from genshi.template import TemplateLoader
from TestPage import TestPage
import logging

loader = TemplateLoader(
    os.path.join(os.path.dirname(__file__), 'templates'),
    auto_reload=True
)

class Root(object):

    test_page = TestPage(loader)

    def __init__(self, data):
        self.data = data

    @cherrypy.expose
    def index(self, **kwargs):
        tmpl = loader.load('index.html')
        return tmpl.generate(title='Index Page', body="This is the index page").render('html', doctype='html')