Esempio n. 1
0
    def __init__(
        self,
        path,
        settings,
        package=None,
        template_class=None,
    ):
        self.path = path
        self.settings = settings
        self.package = package
        self.template_class = template_class

        self.default_domain = self.settings.get('genshi.default_domain')
        auto_reload = asbool(self.settings.get('genshi.auto_reload', True))
        self.loader = TemplateLoader(
            self._load_asset,
            callback=self._tmpl_loaded,
            auto_reload=auto_reload,
        )

        # should we enable i18n?
        i18n = asbool(self.settings.get('genshi.i18n', True))
        if i18n:
            self.adaptor = TranslationStringAdaptor(
                self.localizer.translate,
                self.localizer.pluralize,
                default_domain=self.default_domain
            )
            self.translator = Translator(self.adaptor)
        # no i18n available, just use translator with NullTranslations
        else:
            self.translator = Translator()
Esempio n. 2
0
 def __init__(
     self, 
     path, 
     lookup, 
     macro=None, 
     logger=None, 
     template_class=None,
 ):
     self.logger = logger or logging.getLogger(__name__)
     self.path = path
     self.lookup = lookup
     self.template_class = template_class
     
     # XXX: This is dirty
     self.settings = {}
     registry = get_current_registry()
     if registry is not None:
         self.settings = registry.settings
     self.default_domain = self.settings.get('genshi.default_domain')
     
     # the i18n is available
     if lookup.translate is not None:
         # XXX: This is a very dirty hack, too
         # but this is how Pyramid does - getting request from local thread
         # IChameleonLookup doesn't provide pluralize there, so we need to
         # get by it ourself
         pluralize = None
         if hasattr(lookup, 'pluralize'):
             # pluralize should be added to the lookup, but it is not there
             # see will it be there in the future
             # this is mainly for test right now
             pluralize = lookup.pluralize
         else:
             request = get_current_request()
             if request is not None:
                 pluralize = get_localizer(request).pluralize
         
         self.adaptor = TranslationStringAdaptor(
             lookup.translate, 
             pluralize,
             default_domain=self.default_domain
         )
         self._translator = Translator(self.adaptor)
     # no i18n available, just use translator with NullTranslations
     else:
         self._translator = Translator()
     
     auto_reload = self.settings.get('genshi.auto_reload', True)
     self._loader = TemplateLoader(callback=self._tmpl_loaded, 
                                   auto_reload=auto_reload)
Esempio n. 3
0
    def _add_translation_hook(cls, relatorio_report, context):
        pool = Pool()
        Translation = pool.get('ir.translation')

        translate = TranslateFactory(cls.__name__, Transaction().language,
            Translation)
        context['set_lang'] = lambda language: translate.set_language(language)
        translator = Translator(lambda text: translate(text))
        relatorio_report.filters.insert(0, translator)
Esempio n. 4
0
 def _callback_loader(cls, report, template):
     if report.translatable:
         pool = Pool()
         Translation = pool.get('ir.translation')
         translate = TranslateFactory(cls.__name__, Translation)
         translator = Translator(lambda text: translate(text))
         # Do not use Translator.setup to add filter at the end
         # after set_lang evaluation
         template.filters.append(translator)
         if hasattr(template, 'add_directives'):
             template.add_directives(Translator.NAMESPACE, translator)
Esempio n. 5
0
        def template_loaded(template):
            """Plug-in our i18n function to Genshi, once the template is loaded.

            This function will be called by the Genshi TemplateLoader after
            loading the template.

            """
            translator = Translator(ugettext)
            template.filters.insert(0, translator)
            if hasattr(template, 'add_directives'):
                template.add_directives(Translator.NAMESPACE, translator)
Esempio n. 6
0
 def test_filters(self):
     "Testing the filters with the Translator filter"
     stream = self.oot.generate(**self.data)
     translated = stream.filter(Translator(pseudo_gettext))
     translated_xml = stream_to_string(
         translated.events.render(encoding='utf-8'))
     self.assertTrue("Hello," in translated_xml)
     self.assertTrue("I am an odt templating test" in translated_xml)
     self.assertTrue('Felix da housecat' not in translated_xml)
     self.assertTrue(u'Félix le chat de la maison' in translated_xml)
     self.assertTrue('We sell stuff' not in translated_xml)
     self.assertTrue('On vend des choses' in translated_xml)
Esempio n. 7
0
 def _callback_loader(cls, report, template):
     # JCA: We do not use tranlsation in reports, and this does not work for
     # now with complex directives. See
     # https://support.coopengo.com/issues/20664
     return
     if report.translatable:
         pool = Pool()
         Translation = pool.get('ir.translation')
         translate = TranslateFactory(cls.__name__, Translation)
         translator = Translator(lambda text: translate(text))
         # Do not use Translator.setup to add filter at the end
         # after set_lang evaluation
         template.filters.append(translator)
         if hasattr(template, 'add_directives'):
             template.add_directives(Translator.NAMESPACE, translator)
Esempio n. 8
0
    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)
Esempio n. 9
0
class GenshiTemplateRenderer(object):
    def __init__(
        self,
        path,
        settings,
        package=None,
        template_class=None,
    ):
        self.path = path
        self.settings = settings
        self.package = package
        self.template_class = template_class

        self.default_domain = self.settings.get('genshi.default_domain')
        auto_reload = asbool(self.settings.get('genshi.auto_reload', True))
        self.loader = TemplateLoader(
            self._load_asset,
            callback=self._tmpl_loaded,
            auto_reload=auto_reload,
        )

        # should we enable i18n?
        i18n = asbool(self.settings.get('genshi.i18n', True))
        if i18n:
            self.adaptor = TranslationStringAdaptor(
                self.localizer.translate,
                self.localizer.pluralize,
                default_domain=self.default_domain)
            self.translator = Translator(self.adaptor)
        # no i18n available, just use translator with NullTranslations
        else:
            self.translator = Translator()

    def _load_asset(self, filename):
        """Load pyramid asset resource

        """
        if ':' not in filename:
            raise IOError('Not a asset style path')
        resolver = AssetResolver(self.package)
        filepath = resolver.resolve(filename).abspath()
        fileobj = open(filepath, 'rt')
        mtime = os.path.getmtime(filepath)

        def _uptodate():
            return mtime == os.path.getmtime(filepath)

        return filepath, filename, fileobj, _uptodate

    @property
    def localizer(self):
        request = get_current_request()
        localizer = get_localizer(request)
        return localizer

    def translate(self, *args, **kwargs):
        kwargs.setdefault('domain', self.default_domain)
        ts = TranslationString(*args, **kwargs)
        if self.localizer is not None:
            return self.localizer.translate(ts)
        return ts

    def _tmpl_loaded(self, tmpl):
        """Called when a template is loadded by loader
        
        """
        self.translator.setup(tmpl)

    @property
    def template(self):
        """Loaded Genshi Template
        
        """
        tmpl = self.loader.load(
            os.path.abspath(self.path),
            cls=self.template_class,
        )
        return tmpl

    def render(self, **values):
        """Render template with values
        
        """
        values.setdefault('_', self.translate)
        stream = self.template.generate(**values)
        method = self.settings.get('genshi.method', 'html')
        fmt = self.settings.get('genshi.default_format', method)
        encoding = self.settings.get('genshi.default_encoding', 'utf8')
        doctype = self.settings.get('genshi.default_doctype', None)
        kwargs = {}
        if doctype is not None:
            kwargs['doctype'] = doctype
        body = stream.render(method=fmt, encoding=encoding, **kwargs)
        return body

    def __call__(self, value, system):
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')
        result = self.render(**system)
        return result
Esempio n. 10
0
 def callback(template):
     Translator(lambda s: s.upper()).setup(template)
Esempio n. 11
0
 def template_loaded(template):
     logging.debug('template_loaded: %s', locals())
     template.filters.insert(0, Translator(_))
Esempio n. 12
0
 def template_loaded(template):
     Translator(self.translation).setup(template)
Esempio n. 13
0
class GenshiTemplateRenderer(object):
    implements(ITemplateRenderer)
    
    def __init__(
        self, 
        path, 
        lookup, 
        macro=None, 
        logger=None, 
        template_class=None,
    ):
        self.logger = logger or logging.getLogger(__name__)
        self.path = path
        self.lookup = lookup
        self.template_class = template_class
        
        # XXX: This is dirty
        self.settings = {}
        registry = get_current_registry()
        if registry is not None:
            self.settings = registry.settings
        self.default_domain = self.settings.get('genshi.default_domain')
        
        # the i18n is available
        if lookup.translate is not None:
            # XXX: This is a very dirty hack, too
            # but this is how Pyramid does - getting request from local thread
            # IChameleonLookup doesn't provide pluralize there, so we need to
            # get by it ourself
            pluralize = None
            if hasattr(lookup, 'pluralize'):
                # pluralize should be added to the lookup, but it is not there
                # see will it be there in the future
                # this is mainly for test right now
                pluralize = lookup.pluralize
            else:
                request = get_current_request()
                if request is not None:
                    pluralize = get_localizer(request).pluralize
            
            self.adaptor = TranslationStringAdaptor(
                lookup.translate, 
                pluralize,
                default_domain=self.default_domain
            )
            self._translator = Translator(self.adaptor)
        # no i18n available, just use translator with NullTranslations
        else:
            self._translator = Translator()
        
        auto_reload = self.settings.get('genshi.auto_reload', True)
        self._loader = TemplateLoader(callback=self._tmpl_loaded, 
                                      auto_reload=auto_reload)
                
    def translate(self, *args, **kwargs):
        kwargs.setdefault('domain', self.default_domain)
        ts = TranslationString(*args, **kwargs)
        if self.lookup.translate is not None:
            return self.lookup.translate(ts)
        return ts
        
    def _tmpl_loaded(self, tmpl):
        """Called when a template is loadded by loader
        
        """
        self._translator.setup(tmpl)
        
    @property
    def loader(self):
        """Genshi template loader
        
        """
        return self._loader
        
    @property
    def translator(self):
        """Genshi i18n translator filter
        
        """
        return self._translator

    @property
    def template(self):
        """Loaded Genshi Template
        
        """
        tmpl = self.loader.load(
            os.path.abspath(self.path), 
            cls=self.template_class,
        )
        return tmpl
    
    def render(self, **values):
        """Render template with values
        
        """
        values.setdefault('_', self.translate)
        stream = self.template.generate(**values)
        method = self.settings.get('genshi.method', 'html')
        fmt = self.settings.get('genshi.default_format', method)
        encoding = self.settings.get('genshi.default_encoding', 'utf8')
        kwargs = {}
        doctype = self.settings.get('genshi.default_doctype', None)
        if doctype is not None:
            kwargs['doctype'] = doctype
        body = stream.render(method=fmt, encoding=encoding, **kwargs)
        return body
        
    # implement ITemplateRenderer interface
    def implementation(self):
        return self.render
    
    def __call__(self, value, system):
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')
        result = self.render(**system)
        return result
Esempio n. 14
0
 def template_loaded(template):
     template.filters.insert(0, Translator(i18n))
Esempio n. 15
0
class GenshiTemplateRenderer(object):
    implements(ITemplateRenderer)

    def __init__(self,
                 path,
                 lookup,
                 macro=None,
                 logger=None,
                 template_class=None):
        self.logger = logger or logging.getLogger(__name__)
        self.path = path
        self.lookup = lookup
        self.template_class = template_class

        # XXX: This is dirty
        self.settings = {}
        registry = get_current_registry()
        if registry is not None:
            self.settings = registry.settings
        self.default_domain = self.settings.get('genshi.default_domain')

        # the i18n is available
        if lookup.translate is not None:
            # XXX: This is a very dirty hack, too
            # but this is how Pyramid does - getting request from local thread
            # IChameleonLookup doesn't provide pluralize there, so we need to
            # get by it ourself
            pluralize = None
            if hasattr(lookup, 'pluralize'):
                # pluralize should be added to the lookup, but it is not there
                # see will it be there in the future
                # this is mainly for test right now
                pluralize = lookup.pluralize
            else:
                request = get_current_request()
                if request is not None:
                    pluralize = get_localizer(request).pluralize

            self.adaptor = TranslationStringAdaptor(
                lookup.translate,
                pluralize,
                default_domain=self.default_domain)
            self._translator = Translator(self.adaptor)
        # no i18n available, just use translator with NullTranslations
        else:
            self._translator = Translator()

        auto_reload = self.settings.get('genshi.auto_reload', True)
        self._loader = TemplateLoader(callback=self._tmpl_loaded,
                                      auto_reload=auto_reload)

    def translate(self, *args, **kwargs):
        kwargs.setdefault('domain', self.default_domain)
        ts = TranslationString(*args, **kwargs)
        if self.lookup.translate is not None:
            return self.lookup.translate(ts)
        return ts

    def _tmpl_loaded(self, tmpl):
        """Called when a template is loadded by loader
        
        """
        self._translator.setup(tmpl)

    @property
    def loader(self):
        """Genshi template loader
        
        """
        return self._loader

    @property
    def translator(self):
        """Genshi i18n translator filter
        
        """
        return self._translator

    @property
    def template(self):
        """Loaded Genshi Template
        
        """
        tmpl = self.loader.load(os.path.abspath(self.path),
                                cls=self.template_class)
        return tmpl

    def render(self, **values):
        """Render template with values
        
        """
        values.setdefault('_', self.translate)
        stream = self.template.generate(**values)
        method = self.settings.get('genshi.method', 'html')
        fmt = self.settings.get('genshi.default_format', method)
        encoding = self.settings.get('genshi.default_encoding', 'utf8')
        kwargs = {}
        doctype = self.settings.get('genshi.default_doctype', None)
        if doctype is not None:
            kwargs['doctype'] = doctype
        body = stream.render(method=fmt, encoding=encoding, **kwargs)
        return body

    # implement ITemplateRenderer interface

    def implementation(self):
        return self.render

    def __call__(self, value, system):
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')
        result = self.render(**system)
        return result
Esempio n. 16
0
def genshi_loader_callback(template):
    template.filters.insert(0, Translator(gettext))
Esempio n. 17
0
 def callback(template):
     Translator(translate).setup(template)
Esempio n. 18
0
 def template_loaded(template):
     template.filters.insert(0, Translator(ugettext))
Esempio n. 19
0
class GenshiTemplateRenderer(object):
    
    def __init__(
        self,
        path,
        settings,
        package=None,
        template_class=None,
    ):
        self.path = path
        self.settings = settings
        self.package = package
        self.template_class = template_class

        self.default_domain = self.settings.get('genshi.default_domain')
        auto_reload = asbool(self.settings.get('genshi.auto_reload', True))
        self.loader = TemplateLoader(
            self._load_asset,
            callback=self._tmpl_loaded,
            auto_reload=auto_reload,
        )

        # should we enable i18n?
        i18n = asbool(self.settings.get('genshi.i18n', True))
        if i18n:
            self.adaptor = TranslationStringAdaptor(
                self.localizer.translate,
                self.localizer.pluralize,
                default_domain=self.default_domain
            )
            self.translator = Translator(self.adaptor)
        # no i18n available, just use translator with NullTranslations
        else:
            self.translator = Translator()

    def _load_asset(self, filename):
        """Load pyramid asset resource

        """
        if ':' not in filename:
            raise IOError('Not a asset style path')
        resolver = AssetResolver(self.package)
        filepath = resolver.resolve(filename).abspath()
        fileobj = open(filepath, 'rt')
        mtime = os.path.getmtime(filepath)

        def _uptodate():
            return mtime == os.path.getmtime(filepath)
        return filepath, filename, fileobj, _uptodate

    @property
    def localizer(self):
        request = get_current_request()
        localizer = get_localizer(request)
        return localizer
                
    def translate(self, *args, **kwargs):
        kwargs.setdefault('domain', self.default_domain)
        ts = TranslationString(*args, **kwargs)
        if self.localizer is not None:
            return self.localizer.translate(ts)
        return ts
        
    def _tmpl_loaded(self, tmpl):
        """Called when a template is loadded by loader
        
        """
        self.translator.setup(tmpl)

    @property
    def template(self):
        """Loaded Genshi Template
        
        """
        tmpl = self.loader.load(
            os.path.abspath(self.path),
            cls=self.template_class,
        )
        return tmpl
    
    def render(self, **values):
        """Render template with values
        
        """
        values.setdefault('_', self.translate)
        stream = self.template.generate(**values)
        method = self.settings.get('genshi.method', 'html')
        fmt = self.settings.get('genshi.default_format', method)
        encoding = self.settings.get('genshi.default_encoding', 'utf8')
        doctype = self.settings.get('genshi.default_doctype', None)
        kwargs = {}
        if doctype is not None:
            kwargs['doctype'] = doctype
        body = stream.render(method=fmt, encoding=encoding, **kwargs)
        return body
    
    def __call__(self, value, system):
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')
        result = self.render(**system)
        return result