Ejemplo n.º 1
0
 def render(self, *args, **kwargs):
     """Function to render the given data to the template specified via the
     ``@output`` decorator.
     """
     if args:
         assert len(args) == 1, \
             'Expected exactly one argument, but got %r' % (args,)
         template = self.loader.load(args[0])
     else:
         template = cherrypy.thread_data.template
       
     ua = cherrypy.request.headers.get('user-agent').lower()
   
     if "chrome" in ua:
       browser = "chrome"
     elif "webkit" in ua:
       browser = "safari"
     elif "opera" in ua:
       browser = "opera"
     elif "msie" in ua:
       browser = "msie"
     elif "mozilla" in ua:
       browser = "mozilla"
     else:
       browser = "unknown"
   
     ctxt = Context(url=self.url, request=cherrypy.request, response=cherrypy.response, browser=browser)
     ctxt.push(kwargs)
     return template.generate(ctxt)
Ejemplo n.º 2
0
def render(template_name=None, **kwargs):
    """Function to render the given data to the template specified via the
    ``@output`` decorator.
    """
    if isinstance(template_name, str):
        cherrypy.thread_data.template = loader.load(template_name)
    ctxt = Context(url=cherrypy.url)
    ctxt.push(kwargs)
    return cherrypy.thread_data.template.generate(ctxt)
Ejemplo n.º 3
0
def render(*args, **kwargs):
	if args:
		assert len(args) == 1, \
			'Expected exactly one argument, but got %r' % (args,)
		template = loader.load(args[0])
	else:
		template = cherrypy.thread_data.template
	ctxt = Context(url=cherrypy.url)
	ctxt.push(kwargs)
	return template.generate(ctxt)
Ejemplo n.º 4
0
def render(*args, **kwargs):
    """Function to render the given data to the template specified via the
    ``@output`` decorator.
    """
    if args:
        assert len(args) == 1, 'Expected exactly one argument, but got %r' % (args,)
        template = loader.load(args[0])
    else:
        template = cherrypy.thread_data.template
    ctxt = Context(url=cherrypy.url)
    ctxt.push(kwargs)
    return template.generate(ctxt)
Ejemplo n.º 5
0
def render(*args, **kwargs):
    """Function to render the given data to the template specified via the
    ``@output`` decorator.
    """
    if args:
        assert len(args) == 1, "Expected exactly one argument, but got %r" % (args,)
        template = loader.load(args[0])
    else:
        template = cherrypy.thread_data.template
    ctxt = Context(url=cherrypy.url)
    ctxt.push(kwargs)
    return template.generate(ctxt)
Ejemplo n.º 6
0
 def render(self, *args, **kwargs):
     """Function to render the given data to the template specified via the
     ``@output`` decorator.
     """
     if args:
         assert len(args) == 1, \
             'Expected exactly one argument, but got %r' % (args,)
         template = self._loader.load(args[0])
     else:
         template = thread_data.template
     ctxt = Context(**self.app.tpl_context)
     ctxt.push(kwargs)
     return template.generate(ctxt)
Ejemplo n.º 7
0
def xml_render(*args, **kwargs):
    """Function to render the given data to the template specified via the
    ``@xml`` decorator.
    """
    c = bootstrappy.tmpl_context._current_obj()
    g = bootstrappy.app_globals._current_obj()
    session = bootstrappy.session._current_obj()

    if args:
        assert len(args) == 1,\
        'Expected exactly one argument, but got %r' % (args,)
        template = loader.load(args[0])
    else:
        template = c.template
    ctxt = Context()
    ctxt.push(kwargs)
    return template.generate(g=g, c=c, session=session, *args, **kwargs)
Ejemplo n.º 8
0
def render(*args, **kwargs):
    """
    Function to render the given data to the template specified via the
    ``@output`` decorator.
    """
    if args:
        assert len(args) == 1, \
            'Expected exactly one argument, but got %r' % (args,)
        template = loader.load(args[0])
    else:
        template = cherrypy.thread_data.template
    translator = Translator()
    template.filters.insert(0, translator)
    ctxt = Context(url=cherrypy.url)
    ctxt.push(context_extensions)
    ctxt.push(kwargs)
    cherrypy.response.headers["Content-Type"] = "application/xhtml+xml"
    stream = template.generate(ctxt)
    return stream.render("xhtml")
Ejemplo n.º 9
0
def handle_error_404(status, message, traceback, version):
	from urllib import quote
	from genshi.template import TemplateLoader, Context
	
	template_loader = TemplateLoader(cherrypy.config.get('tools.genshi_template.dir'))
	template = template_loader.load('notfound.html')
	context = Context(url=cherrypy.url, quote=quote)
	stream = template.generate(context)
	
	return stream.render('xhtml')
Ejemplo n.º 10
0
	def __call__(self):
		def replace_at(s):
			import sys
			from genshi.core import Markup
			for kind, data, pos in s:
				if kind == "TEXT" and not isinstance(data, Markup):
					yield kind, data.replace('@', '[snabel-a]'), pos
				else:
					yield kind, data, pos
		
		from urllib import quote
		from genshi.template import Context
		context = Context(url=cherrypy.url, quote=quote)
		context.push(self.next_handler())
		stream = self.template.generate(context)
		if self.type == 'xhtml':
			stream = stream | replace_at
		cherrypy.response.headers['Content-Type'] = { 'xhtml': 'text/html', 'xml': 'application/xml' }[self.type]
		return stream.render(self.type)
Ejemplo n.º 11
0
    def _execute(self):
        from genshi.template import Context, NewTextTemplate
        from genshi.template.eval import UndefinedError

        template = NewTextTemplate(self.source)
        context = Context(parts=self.buildout, options=self.options)
        try:
            self.result = template.generate(context).render()
        except UndefinedError, e:
            raise zc.buildout.UserError("Error in template %s:\n%s" %
                                        (self.input, e.msg))
    def _execute(self):
        from genshi.template import Context, NewTextTemplate
        from genshi.template.eval import UndefinedError

        template = NewTextTemplate(self.source,
                                   filepath=self.input,
                                   filename=self.input)
        context = Context(parts=self.buildout, options=self.options)
        try:
            self.result = template.generate(context).render(encoding='utf-8')
        except UndefinedError, e:
            raise zc.buildout.UserError("Error in template {}:\{}".format(
                self.input, e.msg))
Ejemplo n.º 13
0
Archivo: lib.py Proyecto: cpwnd/odmf
    def __call__(self, *args, **kwargs):
        """Function to render the given data to the template specified via the
        ``@output`` decorator.
        """
        if args:
            assert len(args) == 1, \
                'Expected exactly one argument, but got %r' % (args,)
            template = loader.load(args[0])
        else:
            template = cherrypy.thread_data.template
        ctxt = Context(url=cherrypy.url)
        ctxt.push(kwargs)
        ctxt.push(self.functions)

        # head base for all templates
        # see conf.py
        ctxt.push({'head_base': conf.HEAD_BASE})
        return template.generate(ctxt)
Ejemplo n.º 14
0
 def filter_stream(self, req, method, filename, stream, data):
     if filename == 'wiki_edit.html':
         node = req.args.get('node')
         ctxt = Context(node=node, _=_)
         # field for 'title'
         title_tpl = self.get_loader().load('wiki_edit_title.html')
         title = title_tpl.generate(ctxt)
         stream = stream | Transformer('//div[@id="rows"]').before(title)
         # field for 'parent'
         parent_tpl = self.get_loader().load('wiki_edit_parent.html')
         parent = parent_tpl.generate(ctxt)
         stream = stream | Transformer('//div[@id="changeinfo1"]').before(
             parent)
         # field for 'weight'
         weight_tpl = self.get_loader().load('wiki_edit_weight.html')
         weight = weight_tpl.generate(ctxt)
         stream = stream | Transformer('//div[@id="changeinfo2"]').before(
             weight)
         # field for 'hidden'
         hidden_tpl = self.get_loader().load('wiki_edit_hidden.html')
         hidden = hidden_tpl.generate(ctxt)
         stream = stream | Transformer('//div[@id="changeinfo2"]').before(
             hidden)
     return stream
Ejemplo n.º 15
0
def run(script, doc, output_file=None, options={}):
    """ process an Genshi template """

    context = Context(**options)

    tmpl_fileobj = open(script)
    tmpl = MarkupTemplate(tmpl_fileobj, script)
    tmpl_fileobj.close()

    if not output_file: 
        # filter
        context.push({'input':XMLParser(StringIO(doc))})
    else:
        # template
        import time
        from planet import config,feedparser
        from planet.spider import filename

        # gather a list of subscriptions, feeds
        global subscriptions
        feeds = []
        sources = config.cache_sources_directory()
        for sub in config.subscriptions():
            data=feedparser.parse(filename(sources,sub))
            data.feed.config = norm(dict(config.parser.items(sub)))
            if data.feed.has_key('link'):
                feeds.append((data.feed.config.get('name',''),data.feed))
            subscriptions.append(norm(sub))
        feeds.sort()

        # annotate each entry
        new_date_format = config.new_date_format()
        vars = feedparser.parse(StringIO(doc))
        vars.feeds = [value for name,value in feeds]
        last_feed = None
        last_date = None
        for entry in vars.entries:
             entry.source.config = find_config(config, entry.source)

             # add new_feed and new_date fields
             if 'id' in entry.source:
                 entry.new_feed = entry.source.id
             else:
                 entry.new_feed = None
             entry.new_date = date = None
             if entry.has_key('published_parsed'): date=entry.published_parsed
             if entry.has_key('updated_parsed'): date=entry.updated_parsed
             if date: entry.new_date = time.strftime(new_date_format, date)

             # remove new_feed and new_date fields if not "new"
             if entry.new_date == last_date:
                 entry.new_date = None
                 if entry.new_feed == last_feed:
                     entry.new_feed = None
                 else:
                     last_feed = entry.new_feed
             elif entry.new_date:
                 last_date = entry.new_date
                 last_feed = None

             # add streams for all text constructs
             for key in entry.keys():
                 if key.endswith("_detail") and entry[key].has_key('type') and \
                     entry[key].has_key('value'):
                     streamify(entry[key],entry.source.planet_bozo)
             if entry.has_key('content'):
                 for content in entry.content:
                     streamify(content,entry.source.planet_bozo)
     
        # add cumulative feed information to the Genshi context
        vars.feed.config = dict(config.parser.items('Planet',True))
        context.push(vars)

    # apply template
    output=tmpl.generate(context).render('xml')

    if output_file:
        out_file = open(output_file,'w')
        out_file.write(output)
        out_file.close()
    else:
        return output
Ejemplo n.º 16
0
 def __call__(self):
     context = Context(url=cherrypy.url, quote=quote)
     context.push(self.next_handler())
     stream = self.template.generate(context)
     return stream.render(self.method)
Ejemplo n.º 17
0
 def render(self, template, ns):
     ns.pop('self', None)
     stream = self.loader.load(template).generate(Context(**ns))
     return stream.render(method='xhtml', doctype='xhtml')
Ejemplo n.º 18
0
def run(script, doc, output_file=None, options={}):
    """ process an Genshi template """

    context = Context(**options)

    tmpl_fileobj = open(script)
    tmpl = MarkupTemplate(tmpl_fileobj, script)
    tmpl_fileobj.close()

    if not output_file: 
        # filter
        context.push({'input':XMLParser(StringIO(doc))})
    else:
        # template
        import time
        from planet import config,feedparser
        from planet.spider import filename

        # gather a list of subscriptions, feeds
        global subscriptions
        feeds = []
        sources = config.cache_sources_directory()
        for sub in config.subscriptions():
            data=feedparser.parse(filename(sources,sub))
            data.feed.config = norm(dict(config.parser.items(sub)))
            if data.feed.has_key('link'):
                feeds.append((data.feed.config.get('name',''),data.feed))
            subscriptions.append(norm(sub))
        feeds.sort()

        # annotate each entry
        new_date_format = config.new_date_format()
        vars = feedparser.parse(StringIO(doc))
        vars.feeds = [value for name,value in feeds]
        last_feed = None
        last_date = None
        for entry in vars.entries:
             entry.source.config = find_config(config, entry.source)

             # add new_feed and new_date fields
             entry.new_feed = entry.source.id
             entry.new_date = date = None
             if entry.has_key('published_parsed'): date=entry.published_parsed
             if entry.has_key('updated_parsed'): date=entry.updated_parsed
             if date: entry.new_date = time.strftime(new_date_format, date)

             # remove new_feed and new_date fields if not "new"
             if entry.new_date == last_date:
                 entry.new_date = None
                 if entry.new_feed == last_feed:
                     entry.new_feed = None
                 else:
                     last_feed = entry.new_feed
             elif entry.new_date:
                 last_date = entry.new_date
                 last_feed = None

             # add streams for all text constructs
             for key in entry.keys():
                 if key.endswith("_detail") and entry[key].has_key('type') and \
                     entry[key].has_key('value'):
                     streamify(entry[key],entry.source.planet_bozo)
             if entry.has_key('content'):
                 for content in entry.content:
                     streamify(content,entry.source.planet_bozo)
     
        # add cumulative feed information to the Genshi context
        vars.feed.config = dict(config.parser.items('Planet',True))
        context.push(vars)

    # apply template
    output=tmpl.generate(context).render('xml')

    if output_file:
        out_file = open(output_file,'w')
        out_file.write(output)
        out_file.close()
    else:
        return output