grako / grako / rendering.py

Juancarlo Añez 11ea1bc 
Juancarlo Añez 078a312 



Juancarlo Añez 11ea1bc 
Juancarlo Añez d0b7481 
Juancarlo Añez 752d649 
Juancarlo Añez 2d45c27 
Juancarlo Añez 027fd4c 
Juancarlo Añez e692c33 
Juancarlo Añez 2d45c27 
Juancarlo Añez 167bf91 


Juancarlo Añez 027fd4c 
Juancarlo Añez e692c33 
Juancarlo Añez 027fd4c 
Juancarlo Añez 2d45c27 
Juancarlo Añez 752d649 
Juancarlo Añez 2d45c27 



Juancarlo Añez d0b7481 

Juancarlo Añez e692c33 



Juancarlo Añez d0b7481 
Juancarlo Añez 583b9b0 
Juancarlo Añez 2d45c27 



Juancarlo Añez e0ecb4d 
Juancarlo Añez 91bda68 
Juancarlo Añez 117bbfe 

Juancarlo Añez c55b7df 
Juancarlo Añez 117bbfe 




Juancarlo Añez e0ecb4d 
Juancarlo Añez 7373fc6 
Juancarlo Añez 2d45c27 
Juancarlo Añez c55b7df 
Juancarlo Añez 2d45c27 

# -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim, ustr

def render(item, join='', **fields):
    """ Render the given item
    """
    if item is None:
        return ''
    elif isinstance(item, Renderer):
        return item.render(join=join, **fields)
    elif isinstance(item, list):
        return join.join(render(e, join=join, **fields) for e in item)
    else:
        return ustr(item)


class Renderer(object):
    template = ''
    _counter = itertools.count()

    def __init__(self, template=None):
        if template is not None:
            self.template = template

    def counter(self):
        return next(self._counter)

    def render_fields(self, fields):
        pass

    def render(self, template=None, **fields):
        fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})

        override = self.render_fields(fields)
        if template is None:
            if override is not None:
                template = override
            else:
                template = self.template

        fields.update(fields)
        fields = {k:render(v) for k, v in fields.items()}
        try:
            return trim(template).format(**fields)
        except KeyError as e:
            raise KeyError(str(e), type(self))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.