Example #1
0
def environment(**options):
    env = Environment(**options)
    env.globals.update({"static": staticfiles_storage.url, "url": reverse})
    env.install_gettext_callables(gettext=gettext,
                                  ngettext=ngettext,
                                  newstyle=True)

    env.filters.update({
        "datetime":
        datetime_filter,
        "date":
        date_filter,
        "nl2br":
        nl2br,
        "identify_relation":
        identify_relation,
        "curformat":
        curformat,
        "format_number":
        lambda x: "{:,d}".format(x).replace(",", " "),
        "format_edrpou":
        format_edrpou,
        'uk_plural':
        ukr_plural,
    })
    env.globals.update({
        "updated_querystring": updated_querystring,
        "parse_and_generate": parse_and_generate,
        "generate_all_names": generate_all_names,
        "datasource_pages": get_datasource_pages(),
    })

    return env
Example #2
0
def environment(**options):
    env = Environment(extensions=['jinja2.ext.i18n'], **options)
    env.install_gettext_callables(gettext=gettext_lazy,
                                  ngettext=ngettext_lazy,
                                  newstyle=True)

    from django.template.defaultfilters import register as django_default_register
    env.filters.update(django_default_register.filters)

    from .templatetags.mytags import register
    env.filters.update(register.filters)

    for app_name in settings.INSTALLED_APPS:
        try:
            _register = import_library('%s.%s' % (app_name, 'templatetags'))
            env.filters.update(_register.filters)
        except Exception as e:
            pass

    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
        'reverse': reverse,
        'settings': settings
    })
    return env
Example #3
0
 def _create_env(self, template_dirs, **extra_options):
     env = Environment(loader=FileSystemLoader(template_dirs),
                       extensions=[jinja2.ext.i18n, jinja2.ext.with_],
                       autoescape=True, **extra_options)
     env.install_gettext_callables(gettext=lambda s: s,
                                   ngettext=lambda s: s)
     return env
Example #4
0
class jinja2_renderer_factory(object):
    def __init__(self,
                 search_paths=(),
                 default_templates='deform_jinja2:templates',
                 translator=None,
                 extensions=[]):

        if 'jinja2.ext.i18n' not in extensions:
            extensions.append('jinja2.ext.i18n')

        self.env = Environment(extensions=extensions)
        self.env.loader = FileSystemLoader(())

        for path in search_paths:
            self.add_search_path(path)

        if translator == None:
            translator = DummyTranslator

        self.env.install_gettext_callables(translator.gettext,
                                           translator.ngettext)

        self.add_search_path(default_templates)

    def add_search_path(self, path):
        self.env.loader.searchpath.append(
            resource_filename(*(path.split(':'))))

    def __call__(self, tname, **kw):
        if not '.jinja2' in tname:
            tname += '.jinja2'

        template = self.env.get_template(tname)
        return template.render(**kw)
Example #5
0
class jinja2_renderer_factory(object):
    def __init__(self, search_paths=(), default_templates='deform_jinja2:templates',
            translator=None, extensions=[]):

        if 'jinja2.ext.i18n' not in extensions:
           extensions.append('jinja2.ext.i18n')

        self.env = Environment(extensions=extensions)
        self.env.loader = FileSystemLoader(())

        for path in search_paths:
            self.add_search_path(path)

        if translator == None:
            translator = DummyTranslator

        self.env.install_gettext_callables(translator.gettext, translator.ngettext)

        self.add_search_path(default_templates)

    def add_search_path(self, path):
        self.env.loader.searchpath.append(resource_filename(*(path.split(':'))))

    def add_filter(self, name, func):
        self.env.filters[name] = func

    def __call__(self, tname, **kw):
        if not '.jinja2' in tname:
            tname += '.jinja2'

        template = self.env.get_template(tname)
        return template.render(**kw)
Example #6
0
def build_jinja2_env():
    loader = FileSystemLoader(sys.resources_location)
    env = Environment(loader=loader, extensions=['jinja2.ext.i18n'])
    env.install_gettext_callables(_, _, newstyle=False)
    env.filters['day'] = day_format
    env.globals['csrf_token'] = generate_csrf_token
    return env
Example #7
0
def environment(**options):
    env = Environment(**options)
    env.install_gettext_callables(ugettext, ungettext, newstyle=True)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
    })
    return env
Example #8
0
def render_template(language, context, data, template):
    """Renders HTML display of metadata XML"""

    env = Environment(extensions=["jinja2.ext.i18n"], loader=FileSystemLoader(context.ppath))
    env.install_gettext_callables(gettext, ngettext, newstyle=True)

    template_file = "resources/templates/%s" % template
    template = env.get_template(template_file)
    return template.render(language=language, obj=data)
Example #9
0
 def test_autoescape_support(self):
     env = Environment(extensions=['jinja2.ext.autoescape',
                                   'jinja2.ext.i18n'])
     env.install_gettext_callables(lambda x: u'<strong>Wert: %(name)s</strong>',
                                   lambda s, p, n: s, newstyle=True)
     t = env.from_string('{% autoescape ae %}{{ gettext("foo", name='
                         '"<test>") }}{% endautoescape %}')
     assert t.render(ae=True) == '<strong>Wert: &lt;test&gt;</strong>'
     assert t.render(ae=False) == '<strong>Wert: <test></strong>'
Example #10
0
 def test_autoescape_support(self):
     env = Environment(extensions=['jinja2.ext.autoescape',
                                   'jinja2.ext.i18n'])
     env.install_gettext_callables(lambda x: u'<strong>Wert: %(name)s</strong>',
                                   lambda s, p, n: s, newstyle=True)
     t = env.from_string('{% autoescape ae %}{{ gettext("foo", name='
                         '"<test>") }}{% endautoescape %}')
     assert t.render(ae=True) == '<strong>Wert: &lt;test&gt;</strong>'
     assert t.render(ae=False) == '<strong>Wert: <test></strong>'
Example #11
0
def environment(**options):
    env = Environment(**options)
    env.install_gettext_callables(gettext=gettext,
                                  ngettext=ngettext,
                                  newstyle=True)
    env.globals.update({
        'bs4': bootstrap4,
        'compile': compile_filter,
    })
    return env
Example #12
0
def render_activity_email(activities: list[dict[str, Any]]) -> str:
    globals = {"site_title": config.get_value("ckan.site_title")}
    template_name = "activity_streams/activity_stream_email_notifications.text"

    env = Environment(**jinja_extensions.get_jinja_env_options())
    # Install the given gettext, ngettext callables into the environment
    env.install_gettext_callables(ugettext, ungettext)  # type: ignore

    template = env.get_template(template_name, globals=globals)
    return template.render({"activities": activities})
Example #13
0
def render_template(language, context, data, template):
    """Renders HTML display of metadata XML"""

    env = Environment(extensions=['jinja2.ext.i18n'],
                      loader=FileSystemLoader(context.ppath))
    env.install_gettext_callables(gettext, ngettext, newstyle=True)

    template_file = 'resources/templates/%s' % template
    template = env.get_template(template_file)
    return template.render(language=language, obj=data)
Example #14
0
def _get_or_build_default_environment(registry):
    environment = registry.queryUtility(IJinja2Environment)
    if environment is not None:
        return environment

    settings = registry.settings
    kw = {}
    package = _caller_package(('pyramid_jinja2', 'jinja2', 'pyramid.config'))
    reload_templates = asbool(settings.get('reload_templates', False))
    autoescape = asbool(settings.get('jinja2.autoescape', True))
    domain = settings.get('jinja2.i18n.domain', 'messages')
    debug = asbool(settings.get('debug_templates', False))
    input_encoding = settings.get('jinja2.input_encoding', 'utf-8')

    extensions = parse_multiline(settings.get('jinja2.extensions', ''))
    if 'jinja2.ext.i18n' not in extensions:
        extensions.append('jinja2.ext.i18n')

    directories = parse_multiline(settings.get('jinja2.directories') or '')
    directories = [abspath_from_resource_spec(d, package) for d in directories]
    loader = SmartAssetSpecLoader(
        directories,
        encoding=input_encoding,
        debug=debug)

    # bytecode caching
    bytecode_caching = asbool(settings.get('jinja2.bytecode_caching', True))
    bytecode_caching_directory = settings.get('jinja2.bytecode_caching_directory', None)
    if bytecode_caching:
        kw['bytecode_cache'] = FileSystemBytecodeCache(bytecode_caching_directory)

    defaults_prefix = 'jinja2.defaults.'
    for k, v in settings.items():
        if k.startswith(defaults_prefix):
            kw[k[len(defaults_prefix):]] = v

    environment = Environment(loader=loader,
                              auto_reload=reload_templates,
                              autoescape=autoescape,
                              extensions=extensions,
                              **kw)

    # register pyramid i18n functions
    wrapper = GetTextWrapper(domain=domain)
    environment.install_gettext_callables(wrapper.gettext, wrapper.ngettext)

    # register global repository for templates
    if package is not None:
        environment._default_package = package.__name__

    filters = parse_filters(settings.get('jinja2.filters', ''))
    environment.filters.update(filters)

    registry.registerUtility(environment, IJinja2Environment)
    return registry.queryUtility(IJinja2Environment)
Example #15
0
def build_environment(template):
    env = Environment(
        # undefined=Undefined,
        autoescape=True,
        loader=DictLoader({'tmpl.html': template}),
        extensions=[
            'puente.ext.PuenteI18nExtension'
        ]
    )
    env.install_gettext_callables(gettext, ngettext, newstyle=True)
    return env
Example #16
0
    def __init__(self, app, _globals=None, filters=None):
        self.app = app
        config = app.config[__name__]
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if not kwargs.get('loader'):
            templates_compiled_target = config['templates_compiled_target']
            use_compiled = not app.debug or config['force_use_compiled']

            if templates_compiled_target and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = ModuleLoader(templates_compiled_target)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = FileSystemLoader(config['templates_dir'])

        # Initialize the environment.
        env = Environment(**kwargs)

        if _globals:
            env.globals.update(_globals)

        if filters:
            env.filters.update(filters)

        if enable_i18n:
            # Install i18n.
            from tipfy import i18n
            env.install_gettext_callables(
                lambda x: get_request().i18n.translations.ugettext(x),
                lambda s, p, n: get_request().i18n.translations.ungettext(
                    s, p, n),
                newstyle=True)
            format_functions = {
                'format_date': i18n.format_date,
                'format_time': i18n.format_time,
                'format_datetime': i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            }
            env.globals.update(format_functions)
            env.filters.update(format_functions)

        env.globals['url_for'] = url_for

        after_creation_func = config['after_environment_created']
        if after_creation_func:
            if isinstance(after_creation_func, basestring):
                after_creation_func = import_string(after_creation_func)

            after_creation_func(env)

        environment_created.send(self, environment=env)
        self.environment = env
Example #17
0
    def __init__(self, app, _globals=None, filters=None):
        self.app = app
        config = app.config[__name__]
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if not kwargs.get('loader'):
            templates_compiled_target = config['templates_compiled_target']
            use_compiled = not app.debug or config['force_use_compiled']

            if templates_compiled_target and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = ModuleLoader(templates_compiled_target)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = FileSystemLoader(config['templates_dir'])

        # Initialize the environment.
        env = Environment(**kwargs)

        if _globals:
            env.globals.update(_globals)

        if filters:
            env.filters.update(filters)

        if enable_i18n:
            # Install i18n.
            from tipfy import i18n
            env.install_gettext_callables(
                lambda x: get_request().i18n.translations.ugettext(x),
                lambda s, p, n: get_request().i18n.translations.ungettext(s,
                    p, n),
                newstyle=True)
            format_functions = {
                'format_date':      i18n.format_date,
                'format_time':      i18n.format_time,
                'format_datetime':  i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            }
            env.globals.update(format_functions)
            env.filters.update(format_functions)

        env.globals['url_for'] = url_for

        after_creation_func = config['after_environment_created']
        if after_creation_func:
            if isinstance(after_creation_func, basestring):
                after_creation_func = import_string(after_creation_func)

            after_creation_func(env)

        environment_created.send(self, environment=env)
        self.environment = env
Example #18
0
def _get_or_build_default_environment(registry):
    environment = registry.queryUtility(IJinja2Environment)
    if environment is not None:
        return environment

    settings = registry.settings
    kw = {}
    package = _caller_package(('pyramid_jinja2', 'jinja2', 'pyramid.config'))
    reload_templates = asbool(settings.get('reload_templates', False))
    autoescape = asbool(settings.get('jinja2.autoescape', True))
    domain = settings.get('jinja2.i18n.domain', 'messages')
    debug = asbool(settings.get('debug_templates', False))
    input_encoding = settings.get('jinja2.input_encoding', 'utf-8')

    extensions = parse_multiline(settings.get('jinja2.extensions', ''))
    if 'jinja2.ext.i18n' not in extensions:
        extensions.append('jinja2.ext.i18n')

    undefined = parse_undefined(settings.get('jinja2.undefined', ''))

    directories = parse_multiline(settings.get('jinja2.directories') or '')
    directories = [abspath_from_resource_spec(d, package) for d in directories]
    loader = SmartAssetSpecLoader(directories,
                                  encoding=input_encoding,
                                  debug=debug)

    # bytecode caching
    bytecode_caching = asbool(settings.get('jinja2.bytecode_caching', True))
    bytecode_caching_directory = settings.get(
        'jinja2.bytecode_caching_directory', None)
    if bytecode_caching:
        kw['bytecode_cache'] = FileSystemBytecodeCache(
            bytecode_caching_directory)

    environment = Environment(loader=loader,
                              auto_reload=reload_templates,
                              autoescape=autoescape,
                              extensions=extensions,
                              undefined=undefined,
                              **kw)

    # register pyramid i18n functions
    wrapper = GetTextWrapper(domain=domain)
    environment.install_gettext_callables(wrapper.gettext, wrapper.ngettext)

    # register global repository for templates
    if package is not None:
        environment._default_package = package.__name__

    filters = parse_filters(settings.get('jinja2.filters', ''))
    environment.filters.update(filters)

    registry.registerUtility(environment, IJinja2Environment)
    return registry.queryUtility(IJinja2Environment)
Example #19
0
    def get_body(self, body, signature_template=None):
        from jinja2 import Environment, loaders
        from gettext import gettext, ngettext

        signature = signature_template or settings.EMAIL_SIGNATURE_TEMPLATE
        if not signature:
            return body
        fsloader = loaders.FileSystemLoader(settings.TEMPLATES_DIR)
        environment = Environment(
            extensions=['jinja2.ext.i18n'],
            loader=fsloader)
        environment.install_gettext_callables(gettext, ngettext, newstyle=True)
        template = environment.get_template(signature)
        return unicode('\n'.join((body, template.render())))
Example #20
0
def _setup_environment(registry):
    settings = registry.settings
    reload_templates = asbool(settings.get('reload_templates', False))
    autoescape = asbool(settings.get('jinja2.autoescape', True))
    domain = settings.get('jinja2.i18n.domain', 'messages')
    extensions = _get_extensions(registry)
    filters = parse_filters(settings.get('jinja2.filters', ''))
    environment = Environment(loader=directory_loader_factory(settings),
                              auto_reload=reload_templates,
                              autoescape=autoescape,
                              extensions=extensions)
    wrapper = GetTextWrapper(domain=domain)
    environment.install_gettext_callables(wrapper.gettext, wrapper.ngettext)
    environment.pyramid_jinja2_extensions = extensions
    environment.filters.update(filters)
    registry.registerUtility(environment, IJinja2Environment)
Example #21
0
class Report:
    def __init__(self):
        """Initialize a report object."""
        template_dir = "{basedir}/sixectomy/templates".format(basedir=BASE_DIR)
        self.env = Environment(
            loader=FileSystemLoader(template_dir),
            extensions=["jinja2.ext.i18n"],
            autoescape=select_autoescape(["html", "xml"]),
        )
        self.env.install_gettext_callables(gettext=gettext.gettext,
                                           ngettext=gettext.ngettext,
                                           newstyle=True)

    def rendering(self, template, analyze):
        template = self.env.get_template(template)
        print(template.render(analyze=analyze))
Example #22
0
class TemplateManager(object):
    """
    Uses to generate HTML page from template using Jinja2 templating.
    """

    def __init__(self):

        loader = ChoiceLoader([
            PackageLoader('rdiffweb', 'templates')
        ])

        # Load all the templates from /templates directory
        self.jinja_env = Environment(
            loader=loader,
            auto_reload=True,
            autoescape=True,
            extensions=[
                'jinja2.ext.i18n',
                'jinja2.ext.with_',
                'jinja2.ext.autoescape',
            ])

        # Register filters
        self.jinja_env.filters['filter'] = do_filter
        self.jinja_env.filters['datetime'] = do_format_datetime
        self.jinja_env.filters['filesize'] = do_format_filesize

        # Register method
        self.jinja_env.globals['attrib'] = attrib
        self.jinja_env.globals['create_repo_tree'] = create_repo_tree
        self.jinja_env.globals['url_for'] = url_for

    def compile_template(self, template_name, **kwargs):
        """Very simple implementation to render template using jinja2.
            `templateName`
                The filename to be used as template.
            `kwargs`
                The arguments to be passed to the template.
        """
        logger.log(1, "compiling template [%s]", template_name)
        self.jinja_env.install_gettext_callables(
            i18n.ugettext, i18n.ungettext, newstyle=True)
        template = self.jinja_env.get_template(template_name)
        data = template.render(kwargs)
        logger.log(1, "template [%s] compiled", template_name)
        return data
Example #23
0
def _setup_environment(registry):
    settings = registry.settings
    reload_templates = asbool(settings.get('reload_templates', False))
    autoescape = asbool(settings.get('jinja2.autoescape', True))
    extensions = _get_extensions(registry)
    filters = parse_filters(settings.get('jinja2.filters', ''))
    environment = Environment(loader=directory_loader_factory(settings),
                              auto_reload=reload_templates,
                              autoescape=autoescape,
                              extensions=extensions)
    hook = GetTextHook()
    environment.install_gettext_callables(hook.gettext, hook.ngettext)
    environment.pyramid_jinja2_extensions = extensions
    package = _caller_package(('pyramid_jinja2', 'jinja2', 'pyramid.config'))
    if package is not None:
        environment._default_package = package.__name__
    environment.filters.update(filters)
    registry.registerUtility(environment, IJinja2Environment)
Example #24
0
def _setup_environment(registry):
    settings = registry.settings
    reload_templates = asbool(settings.get('reload_templates', False))
    autoescape = asbool(settings.get('jinja2.autoescape', True))
    extensions = _get_extensions(registry)
    filters = parse_filters(settings.get('jinja2.filters', ''))
    environment = Environment(loader=directory_loader_factory(settings),
                              auto_reload=reload_templates,
                              autoescape=autoescape,
                              extensions=extensions)
    hook = GetTextHook()
    environment.install_gettext_callables(hook.gettext, hook.ngettext)
    environment.pyramid_jinja2_extensions = extensions
    package = _caller_package(('pyramid_jinja2', 'jinja2', 'pyramid.config'))
    if package is not None:
        environment._default_package = package.__name__
    environment.filters.update(filters)
    registry.registerUtility(environment, IJinja2Environment)
Example #25
0
def environment(**options):
    options.pop('debug', None)
    options['extensions'] = ['jinja2.ext.i18n']
    # options['enable_async'] = True
    env = Environment(**options)
    env.globals.update({
        'static': static,
        'url': reverse,
        'FACEBOOK_APP_ID': 'pedo',
        'HOME_URL': settings.HOME_URL,
        'STATIC_URL': settings.STATIC_URL,
        'dividir_columnas': dividir_columnas,
        'partition_horizontal': partition_horizontal,
        'uslugify': slugify,
        'get_current_language': translation.get_language,
    })
    env.install_gettext_callables(gettext=gettext, ngettext=ngettext, newstyle=True)
    return env
def create_jinja2_instance():
    """Returns the Jinja2 environment.

    :return:
        A ``jinja2.Environment`` instance.
    """
    app = Tipfy.app
    cfg = app.get_config(__name__)
    templates_compiled_target = cfg.get('templates_compiled_target')
    use_compiled = not app.dev or cfg.get( 'force_use_compiled')

    if templates_compiled_target is not None and use_compiled:
        # Use precompiled templates loaded from a module or zip.
        loader = ModuleLoader(templates_compiled_target)
    else:
        # Parse templates for every new environment instances.
        loader = FileSystemLoader(cfg.get( 'templates_dir'))

    if i18n:
        extensions = ['jinja2.ext.i18n']
    else:
        extensions = []

    # Initialize the environment.
    env = Environment(loader=loader, extensions=extensions)

    # Add url_for() by default.
    env.globals['url_for'] = url_for

    if i18n:
        # Install i18n.
        trans = i18n.get_translations
        env.install_gettext_callables(
            lambda s: trans().ugettext(s),
            lambda s, p, n: trans().ungettext(s, p, n),
            newstyle=True)
        env.globals.update({
            'format_date':     i18n.format_date,
            'format_time':     i18n.format_time,
            'format_datetime': i18n.format_datetime,
        })

    return env
Example #27
0
def create_jinja2_instance():
    """Returns the Jinja2 environment.

    :return:
        A ``jinja2.Environment`` instance.
    """
    app = Tipfy.app
    cfg = app.get_config(__name__)
    templates_compiled_target = cfg.get("templates_compiled_target")
    use_compiled = not app.dev or cfg.get("force_use_compiled")

    if templates_compiled_target is not None and use_compiled:
        # Use precompiled templates loaded from a module or zip.
        loader = ModuleLoader(templates_compiled_target)
    else:
        # Parse templates for every new environment instances.
        loader = FileSystemLoader(cfg.get("templates_dir"))

    if i18n:
        extensions = ["jinja2.ext.i18n"]
    else:
        extensions = []

    # Initialize the environment.
    env = Environment(loader=loader, extensions=extensions)

    # Add url_for() by default.
    env.globals["url_for"] = url_for

    if i18n:
        # Install i18n.
        trans = i18n.get_translations
        env.install_gettext_callables(
            lambda s: trans().ugettext(s), lambda s, p, n: trans().ungettext(s, p, n), newstyle=True
        )
        env.globals.update(
            {"format_date": i18n.format_date, "format_time": i18n.format_time, "format_datetime": i18n.format_datetime}
        )

    return env
Example #28
0
    def __init__(self, app, _globals=None, filters=None):
        self.app = app
        config = app.config[__name__]
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if not kwargs.get('loader'):
            templates_compiled_target = config['templates_compiled_target']
            use_compiled = not app.debug or config['force_use_compiled']

            if templates_compiled_target and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = ModuleLoader(templates_compiled_target)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = FileSystemLoader(config['templates_dir'])

        # Initialize the environment.
        env = Environment(**kwargs)

        if _globals:
            env.globals.update(_globals)

        if filters:
            env.filters.update(filters)

        if enable_i18n:
            # Install i18n.
            from tipfy import i18n
            env.install_gettext_callables(i18n.gettext, i18n.ngettext,
                newstyle=True)
            env.filters.update({
                'format_date':      i18n.format_date,
                'format_time':      i18n.format_time,
                'format_datetime':  i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            })

        env.globals['url_for'] = url_for
        self.environment = env
Example #29
0
def environment(**options):
    env = Environment(**options)
    env.globals.update({"static": staticfiles_storage.url, "url": reverse})
    env.install_gettext_callables(gettext=gettext,
                                  ngettext=ngettext,
                                  newstyle=True)

    env.filters.update({
        "datetime": datetime_filter,
        "date": date_filter,
        "title": title,
        "uk_plural": ukr_plural,
        "curformat": curformat,
        "format_phone": format_phone,
        "truncate_phone": truncate_phone,
    })
    env.globals.update({
        "updated_querystring": updated_querystring,
        "parse_and_generate": parse_and_generate,
    })

    return env
Example #30
0
def environment(**options):
    env = Environment(**options)
    env.globals.update({
        "static": staticfiles_storage.url,
        "url": reverse,
        "curr_year": datetime.today().year,
    })
    env.install_gettext_callables(gettext=gettext,
                                  ngettext=ngettext,
                                  newstyle=True)
    env.add_extension(LanguageExtension)

    env.policies["json.dumps_function"] = datetime_dumps

    env.filters.update({
        "datetime": datetime_filter,
        "date": date_filter,
        "number_format": number_format,
        "excerpt_markdown": excerpt_markdown,
        "markdown": markdown_filter,
    })

    return env
Example #31
0
def env(templates_dir):
    jinja_env = Env(loader=FileSystemLoader(templates_dir),
                    extensions=['jinja2.ext.i18n',"jinja2.ext.do"])
# Era un parametro della classe Env  bytecode_cache=FileSystemBytecodeCache(os.path.join(Environment.promogestDir, 'temp'), '%s.cache'),
    jinja_env.globals['environment'] = Environment
    jinja_env.globals['utils'] = utils
    jinja_env.globals['daoutils'] = daoutils
    jinja_env.globals['datetime'] = datetime
    jinja_env.filters['dateformat'] = dateformat
    jinja_env.filters['datetimeformat'] = datetimeformat
    jinja_env.filters['nl2br'] = nl2br
    jinja_env.filters['nonone'] = noNone
    jinja_env.filters['uu'] = uu
    try:
        # installa gettext per i18n
        jinja_env.install_gettext_callables(_, ngettext, newstyle=True)
        jinja_env.globals.update({
            '_': _,
            'ngettext': ngettext
        })
    except:
        pass
    return jinja_env
Example #32
0
def environment(**options):
    env = Environment(**options)
    env.globals.update({"static": staticfiles_storage.url, "url": reverse})
    env.install_gettext_callables(gettext=gettext,
                                  ngettext=ngettext,
                                  newstyle=True)

    env.filters.update({
        "datetime":
        datetime_filter,
        "date":
        date_filter,
        "nl2br":
        nl2br,
        "format_number":
        lambda x: "{:,d}".format(x).replace(",", " "),
        'uk_plural':
        ukr_plural,
    })
    env.globals.update({
        "updated_querystring": updated_querystring,
    })

    return env
Example #33
0
            "violations": violations,
        }


# Set up the template environment
TEMPLATE_LOADER = PackageLoader(__package__)
TEMPLATE_ENV = Environment(
    extensions=["jinja2.ext.i18n"],
    loader=TEMPLATE_LOADER,
    trim_blocks=True,
    lstrip_blocks=True,
)

# pylint thinks this callable does not exist, I assure you it does
TEMPLATE_ENV.install_gettext_callables(  # pylint: disable=no-member
    gettext=gettext,
    ngettext=ngettext,
    newstyle=True)


class JsonReportGenerator(BaseReportGenerator):
    def generate_report(self, output_file):
        json_report_str = json.dumps(self.report_dict())

        # all report generators are expected to write raw bytes, so we encode
        # the json
        output_file.write(json_report_str.encode("utf-8"))


class TemplateReportGenerator(BaseReportGenerator):
    """
    Reporter that uses a template to generate the report.
Example #34
0
bcrypt = Bcrypt(app)

login_manager = LoginManager()
login_manager.init_app(app)

dirname = os.path.dirname(os.path.abspath(__file__))
migration_dir = os.path.join(dirname, "migrations")

migrate = Migrate(app, Base, directory=migration_dir)

template_env = Environment(
    loader=FileSystemLoader("%s/templates/" % os.path.dirname(__file__)),
    extensions=["jinja2.ext.i18n"],
)
template_env.install_gettext_callables(gettext=_, ngettext=ngettext)

limiter = Limiter(app, key_func=get_remote_address)

cache_region = make_region().configure(
    "dogpile.cache.redis",
    arguments={
        "host": os.environ.get("REDIS_HOST"),
        "port": os.environ.get("REDIS_PORT"),
        "redis_expiration_time": 60 * 60 * 2,  # 2 hours
        "distributed_lock": True,
        "thread_local_lock": False,
    },
)

from app.schema import schema
Example #35
0
def _get_or_build_default_environment(registry):
    environment = registry.queryUtility(IJinja2Environment)
    if environment is not None:
        return environment

    settings = registry.settings
    kw = {}

    package = _caller_package(('pyramid_jinja2', 'jinja2', 'pyramid.config'))
    debug = asbool(settings.get('debug_templates', False))

    # get basic environment jinja2 settings
    kw.update(_parse_config_for_settings(settings))
    reload_templates = settings.get('reload_templates', None)
    if reload_templates is None:
        # since version 1.5, both settings are supported
        reload_templates = settings.get('pyramid.reload_templates', False)
    reload_templates = asbool(reload_templates)
    undefined = parse_undefined(settings.get('jinja2.undefined', ''))

    # get supplementary junja2 settings
    input_encoding = settings.get('jinja2.input_encoding', 'utf-8')
    domain = settings.get('jinja2.i18n.domain', package and package.__name__ or 'messages')

    # get jinja2 extensions
    extensions = parse_multiline(settings.get('jinja2.extensions', ''))
    if 'jinja2.ext.i18n' not in extensions:
        extensions.append('jinja2.ext.i18n')

    # get jinja2 directories
    directories = parse_multiline(settings.get('jinja2.directories') or '')
    directories = [abspath_from_resource_spec(d, package) for d in directories]
    loader = SmartAssetSpecLoader(
        directories,
        encoding=input_encoding,
        debug=debug)

    # get jinja2 bytecode caching settings and set up bytecaching
    bytecode_caching = asbool(settings.get('jinja2.bytecode_caching', True))
    bytecode_caching_directory = \
        settings.get('jinja2.bytecode_caching_directory', None)
    if bytecode_caching:
        kw['bytecode_cache'] = \
            FileSystemBytecodeCache(bytecode_caching_directory)
        # clear cache on exit
        atexit.register(kw['bytecode_cache'].clear)

    # should newstyle gettext calls be enabled?
    newstyle = asbool(settings.get('jinja2.newstyle', False))

    environment = Environment(loader=loader,
                              auto_reload=reload_templates,
                              extensions=extensions,
                              undefined=undefined,
                              **kw)

    # register pyramid i18n functions
    wrapper = GetTextWrapper(domain=domain)
    environment.install_gettext_callables(wrapper.gettext, wrapper.ngettext, newstyle=newstyle)

    # register global repository for templates
    if package is not None:
        environment._default_package = package.__name__

    #add custom jinja2 filters
    filters = parse_config(settings.get('jinja2.filters', ''))
    environment.filters.update(filters)

    #add custom jinja2 tests
    tests = parse_config(settings.get('jinja2.tests', ''))
    environment.tests.update(tests)

    # add custom jinja2 functions
    jinja_globals = parse_config(settings.get('jinja2.globals', ''))
    environment.globals.update(jinja_globals)

    registry.registerUtility(environment, IJinja2Environment)
    return registry.queryUtility(IJinja2Environment)
Example #36
0
    except Exception as ex:
        log.error(ex)
    finally:
        if tmpn is not None and os.path.exists(tmpn):
            try:
                os.unlink(tmpn)
            except Exception as ex:
                log.warn(ex)
    return False


site_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "site")
env = Environment(loader=PackageLoader(__package__, 'templates'),
                  extensions=['jinja2.ext.i18n'])
env.install_gettext_callables(i18n.language.gettext,
                              i18n.language.ngettext,
                              newstyle=True)


def urlencode_filter(s):
    if type(s) == 'Markup':
        s = s.unescape()
    s = s.encode('utf8')
    s = urllib.quote_plus(s)
    return Markup(s)


def truncate_filter(s, max_len=10):
    if len(s) > max_len:
        return s[0:max_len] + "..."
    else:
Example #37
0
cli = parser.parse_args()


def guess_autoescape(template_name):
    if template_name is None or '.' not in template_name:
        return False
    ext = template_name.rsplit('.', 1)[1]
    return ext in ('html', 'htm', 'xml')


env = Environment(autoescape=guess_autoescape,
                  loader=FileSystemLoader(cli.templates),
                  extensions=['jinja2.ext.autoescape', 'jinja2.ext.i18n'])
env.install_gettext_callables(
    lambda x: get_translations().ugettext(x),
    lambda s, p, n: get_translations().ungettext(s, p, n),
    newstyle=True)


def build():

    try:
        mappings, _ = parse_mapping(open(cli.babelconf))
    except IOError:
        sys.exit("Could not find Babel conf ({0})".format(cli.babelconf))

    search_paths = [search_path for (search_path, _) in mappings]

    def is_template(name):
        full_name = os.path.join(cli.templates, name)
        for path in search_paths:
Example #38
0
def generate_file(task_id, app_url='http://localhost:9000', file_format='PDF', lang='en'):

    from rdr.modules.users.session import session_user
    from rdr.modules.feeds.models import OfflineReadQueueTask
    task = OfflineReadQueueTask.query.filter(OfflineReadQueueTask.id == task_id).one()
    user = task.user
    session_user.auth(user)

    from rdr.application.i18n import format_datetime, gettext, ngettext, set_global_lang
    set_global_lang(lang)

    from rdr.application.database import db
    from rdr.modules.feeds.models import Article, OfflineReadQueue
    from rdr.modules.feeds.articles.status import UserArticleRecord

    articles = Article.query \
        .join(OfflineReadQueue, (OfflineReadQueue.user_id == user.id) & (OfflineReadQueue.article_id == Article.id)) \
        .options(db.joinedload(Article.statuses),
                 db.joinedload(Article.feed)) \
        .filter((Article.active == True)).order_by(OfflineReadQueue.add_date.asc())

    records = UserArticleRecord.wrap_articles_list(articles)
    dicts = [x.to_dict(full_text=True) for x in records]

    if not dicts:
        task.status = OfflineReadQueueTask.STATUS_REJECTED
        db.session.commit()
        return False

    from jinja2 import Environment, FileSystemLoader
    import os
    from datetime import datetime

    env = Environment(extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape', 'jinja2.ext.with_'], autoescape=True, loader=FileSystemLoader(
        os.path.join(os.path.dirname(os.path.realpath(__file__)),
                     '..',
                     '..',
                     'modules',
                     'feeds',
                     'templates',
                     'offline-reading')
        )
    )
    env.install_gettext_callables(gettext, ngettext, True)
    template = env.get_template('pdf-std.jhtml')
    content = template.render(articles=dicts,
                              url=app_url,
                              username=user.username,
                              gen_date=format_datetime(datetime.now(), 'dd MMM yyyy HH:mm'))

    import pdfkit
    from tempfile import NamedTemporaryFile

    pdf_opts = {
        'page-size': 'Letter'
    }
    f = NamedTemporaryFile(delete=False)
    pdfkit.from_string(content, f.name, options=pdf_opts)
    task.status = OfflineReadQueueTask.STATUS_FILE_GENERATED
    task.out_file = f.name
    db.session.commit()
    return True
Example #39
0
i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])

i18n_env_trimmed.policies["ext.i18n.trimmed"] = True
i18n_env_trimmed.globals.update({
    "_": gettext,
    "gettext": gettext,
    "ngettext": ngettext,
    "pgettext": pgettext,
    "npgettext": npgettext,
})

newstyle_i18n_env = Environment(loader=DictLoader(newstyle_i18n_templates),
                                extensions=["jinja2.ext.i18n"])
newstyle_i18n_env.install_gettext_callables(  # type: ignore
    gettext,
    ngettext,
    newstyle=True,
    pgettext=pgettext,
    npgettext=npgettext)


class ExampleExtension(Extension):
    tags = {"test"}
    ext_attr = 42
    context_reference_node_cls = nodes.ContextReference

    def parse(self, parser):
        return nodes.Output([
            self.call_method(
                "_dump",
                [
                    nodes.EnvironmentAttribute("sandboxed"),
Example #40
0
File: utils.py Project: br00k/pyFF
            os.rename(tmpn, fn)
            return True
    except Exception, ex:
        log.error(ex)
    finally:
        if tmpn is not None and os.path.exists(tmpn):
            try:
                os.unlink(tmpn)
            except Exception, ex:
                log.warn(ex)
    return False


site_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "site")
env = Environment(loader=PackageLoader(__package__, 'templates'), extensions=['jinja2.ext.i18n'])
env.install_gettext_callables(i18n.language.gettext, i18n.language.ngettext, newstyle=True)

import urllib
from markupsafe import Markup


def urlencode_filter(s):
    if type(s) == 'Markup':
        s = s.unescape()
    s = s.encode('utf8')
    s = urllib.quote_plus(s)
    return Markup(s)

def truncate_filter(s,max_len=10):
    if len(s) > max_len:
        return s[0:max_len]+"..."
Example #41
0
import datetime
import xdm
from fileBrowser import WebFileBrowser
from wizard import Wizard

from ajax import AjaxCalls
from jinja2 import Environment, FileSystemLoader
from xdm.classes import *
from xdm import common, tasks, helper
from xdm.logger import *
from xdm import actionManager
from xdm.api import WebApi


env = Environment(loader=FileSystemLoader(os.path.join('html', 'templates')), extensions=['jinja2.ext.i18n'])
env.install_gettext_callables(_, ngettext, newstyle=True)
env.filters['idSafe'] = helper.idSafe
env.filters['statusLabelClass'] = helper.statusLabelClass
env.filters['vars'] = helper.webVars
env.filters['relativeTime'] = helper.reltime
env.filters['dereferMe'] = helper.dereferMe
env.filters['dereferMeText'] = helper.dereferMeText


def stateCheck():
    if xdm.xdm_states[7] in xdm.common.STATES:
        r = cherrypy.request
        if not r.path_info.startswith('/wizard'):
            for path in common.PUBLIC_PATHS + ['/ajax']:
                if r.path_info.startswith(path) and len(r.path_info) > 1:
                    #print 'path looks fine %s' % r.path_info
Example #42
0
i18n_env = Environment(
    loader=DictLoader(i18n_templates),
    extensions=['jinja2.ext.i18n']
)
i18n_env.globals.update({
    '_':            gettext,
    'gettext':      gettext,
    'ngettext':     ngettext
})

newstyle_i18n_env = Environment(
    loader=DictLoader(newstyle_i18n_templates),
    extensions=['jinja2.ext.i18n']
)
newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)

class TestExtension(Extension):
    tags = set(['test'])
    ext_attr = 42

    def parse(self, parser):
        return nodes.Output([self.call_method('_dump', [
            nodes.EnvironmentAttribute('sandboxed'),
            self.attr('ext_attr'),
            nodes.ImportedName(__name__ + '.importable_object'),
            nodes.ContextReference()
        ])]).set_lineno(next(parser.stream).lineno)

    def _dump(self, sandboxed, ext_attr, imported_object, context):
        return '%s|%s|%s|%s' % (
Example #43
0
from jinja2 import Environment, FileSystemLoader
from markdown import markdown
from markupsafe import Markup

PATH = Path(__file__).parent

#
# Create default environment.
#
env = Environment(
    loader=FileSystemLoader(PATH / "templates"),
    trim_blocks=True,
    lstrip_blocks=True,
    extensions=["jinja2.ext.i18n"],
)
env.install_gettext_callables(gettext, ngettext)
env.globals["markdown"] = markdown
env.filters["markdown"] = markdown


#
# Functions
#
def jinja_function(fn):
    """
    Register function in the global environment.
    """
    env.globals[fn.__name__] = fn
    return fn

Example #44
0
class TemplateManager(object):
    """
    Uses to generate HTML page from template using Jinja2 templating.
    """
    def __init__(self):

        loader = ChoiceLoader([PackageLoader('rdiffweb', 'templates')])

        # Load all the templates from /templates directory
        self.jinja_env = Environment(loader=loader,
                                     auto_reload=True,
                                     autoescape=True,
                                     extensions=[
                                         'jinja2.ext.i18n',
                                         'jinja2.ext.with_',
                                         'jinja2.ext.autoescape',
                                     ])

        # Register filters
        self.jinja_env.filters['filter'] = do_filter
        self.jinja_env.filters['datetime'] = do_format_datetime
        self.jinja_env.filters['filesize'] = do_format_filesize

        # Register method
        self.jinja_env.globals['attrib'] = attrib
        self.jinja_env.globals['url_for_browse'] = url_for_browse
        self.jinja_env.globals['url_for_history'] = url_for_history
        self.jinja_env.globals['url_for_restore'] = url_for_restore
        self.jinja_env.globals['url_for_settings'] = url_for_settings
        self.jinja_env.globals['url_for_status_entry'] = url_for_status_entry

    def add_templatesdir(self, templates_dir):
        """
        Add a new templates directory.
        """
        # Add a new template location to the list of loaders.
        loaders = self.jinja_env.loader.loaders
        loaders.append(FileSystemLoader(templates_dir))

    def compile_template(self, template_name, **kwargs):
        """Very simple implementation to render template using jinja2.
            `templateName`
                The filename to be used as template.
            `kwargs`
                The arguments to be passed to the template.
        """
        logger.log(1, "compiling template [%s]", template_name)
        self.jinja_env.install_gettext_callables(i18n.ugettext,
                                                 i18n.ungettext,
                                                 newstyle=True)
        template = self.jinja_env.get_template(template_name)
        data = template.render(kwargs)
        logger.log(1, "template [%s] compiled", template_name)
        return data

    def get_template(self, template_name):
        """
        Return a reference to the given template identify by `template_name`.
        This method is commonly used by plugins. If the `template_name` is not
        found an error is raised.
        """
        # Simply use the jinja env to return reference to template.
        return self.jinja_env.get_template(template_name)
Example #45
0
class AnguineApp(object):
    """
    An interface to application.
    """

    def __init__(self, url_handler_modules=[], application_events_config={}, facebook_social_config={}, twitter_social_config={},
                    languages_config={}, version='0.1'):
        app_folder = None
        try:
            frame = inspect.currentframe()
            f_back = frame.f_back
            name = f_back.f_globals['__name__']
            app_folder = inspect.getframeinfo(f_back)[0]
            logging.info('!!!!!!!!!Initialize app: %s', name)
            self.name = name

        finally:
            del frame, f_back

        self.version = version

        self.local = Local()

        self._urls = []

        self.views = {}

        self.facebook_options = facebook_social_config
        self.twitter_options = twitter_social_config

        for url_handler_module in url_handler_modules:
            self.add_url_handler_module(url_handler_module)

        self.urls = {}
        for i in xrange(0, len(self._urls), 2):
            self.urls[self._urls[i + 1]] = self._urls[i]

        self.template_path = path.join(path.dirname(app_folder), '../resources/templates')

        self.jinja_env = Environment(loader=FileSystemLoader(self.template_path),
                                     extensions=['jinja2.ext.i18n'])

        self.language_path = path.dirname(app_folder)
        sys.path.append(self.language_path)
        logging.info("language_path: %s", self.language_path)

        languages = languages_config
        self.languages = languages
        self.available_languages = languages.keys()
        self.available_languages.remove('default')
        self.default_language = languages.get('default', 'en')

        @contextfunction
        def gettext(context, string):
            language = context.get('LANGUAGE', 'en')

            return languages.get(language, {}).get(string, string)


        @contextfunction
        def ngettext(context, s, p, n):
            language = context.get('LANGUAGE', 'en')

            if n != 1:
                return languages.get(language, {}).get(p, p)
            return languages.get(language, {}).get(s, s)

        self.jinja_env.install_gettext_callables(gettext, ngettext, newstyle=True)


        def url_for(endpoint, _external=False, **values):
            return self.local.url_adapter.build(endpoint, values, force_external=_external)
        self.jinja_env.globals['url_for'] = url_for
        self.url_for = url_for

        def url_image(_external=False, **values):
            return self.local.url_adapter.build('images', values, force_external=_external)
        self.jinja_env.globals['url_image'] = url_image
        self.url_image = url_image


        self.url_map = Map([
            Rule('/css/<file>', endpoint='css', build_only=True),
            Rule('/js/<file>', endpoint='js', build_only=True),
            Rule('/img/<file>', endpoint='images', build_only=True),
            Rule('/processing/<file>', endpoint='processing', build_only=True),
            Rule('/flash/<file>', endpoint='flash', build_only=True),
            Rule('/sound/<file>', endpoint='sound', build_only=True),

        ])

        url_map = [(self._urls[i], self._urls[i + 1])
                     for i in xrange(0, len(self._urls), 2)]

        for key, view in self.views.iteritems():
            if (hasattr(view, 'urls')):
                logging.info('add view.urls: %s', view.urls)
                for url in view.urls:
                    url_map.append((url, key))

        for regex, view in url_map:
            logging.info("regex: %s, view: %s", regex, view)
            self.url_map.add(Rule(regex, endpoint=view))

        self.app_event_handlers = application_events_config

        self.on_app_start()


    def on_app_start(self):
        if self.app_event_handlers and ON_APP_START in self.app_event_handlers:
            self.app_event_handlers[ON_APP_START](self)
        pass


    def handle_not_found(self, request=None):
        resp = Response('Not found')
        resp.status_code = 404
        return resp


    def handle_other_error(self, request=None):
        resp = Response('Other error')
        resp.status_code = 500
        return resp


    def add_url_handler_module(self, url_handler_module):
        views = [view_class
                     for (name, view_class) in inspect.getmembers(url_handler_module, inspect.isclass)
                        if (issubclass(view_class, TemplateView) or issubclass(view_class, JSONHandler)
                            or issubclass(view_class, TaskHandler))]

        for view in views:
            if (hasattr(view, '__name__')):
                self.views[view.__name__[0].lower() + view.__name__[1:]] = view


    def __call__(self, environ, start_response):
        req = None

        try:
            req = Request(environ)
            self.local.url_adapter = self.url_map.bind_to_environ(environ)

            endpoint, args = self.local.url_adapter.match()
            logging.info("endpoint: %s, args: %s", endpoint, args)

            if endpoint is not None:
                if req.method not in ('GET', 'HEAD', 'POST',
                                      'DELETE', 'PUT'):
                    raise NotImplemented()
                view = self.views[endpoint](self, req)
                resp = getattr(view, req.method.lower())(**args)

            else:
                raise NotFound()

        except NotFound:
            logging.info("NotFound")
            resp = self.handle_not_found(req)

        except HTTPException:
            logging.info("HTTPException")
            resp = self.handle_other_error(req)

        return resp(environ, start_response)
Example #46
0
i18n_env.globals.update({
    "_": gettext,
    "gettext": gettext,
    "ngettext": ngettext
})
i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])
i18n_env_trimmed.policies["ext.i18n.trimmed"] = True
i18n_env_trimmed.globals.update({
    "_": gettext,
    "gettext": gettext,
    "ngettext": ngettext
})

newstyle_i18n_env = Environment(loader=DictLoader(newstyle_i18n_templates),
                                extensions=["jinja2.ext.i18n"])
newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)


class ExampleExtension(Extension):
    tags = set(["test"])
    ext_attr = 42
    context_reference_node_cls = nodes.ContextReference

    def parse(self, parser):
        return nodes.Output([
            self.call_method(
                "_dump",
                [
                    nodes.EnvironmentAttribute("sandboxed"),
                    self.attr("ext_attr"),
                    nodes.ImportedName(__name__ + ".importable_object"),
Example #47
0
def Localize(source, locales, options):
  # Set the list of languages to use.
  languages = map(NormalizeLanguageCode, locales)
  context = { 'languages' : languages }

  # Load the localized messages.
  message_map = MessageMap(languages, options.locale_dir)

  # Add OFFICIAL_BUILD variable the same way chrome/tools/build/version.py
  # does.
  if os.environ.get('CHROME_BUILD_TYPE') == '_official':
    context['official_build'] = '1'
  else:
    context['official_build'] = '0'

  # Add all variables defined in the command line.
  if options.define:
    for define in options.define:
      context.update(dict([define.split('=', 1)]));

  # Read NAME=VALUE variables from file.
  if options.variables:
    for file_name in options.variables:
      ReadValuesFromFile(context, file_name)

  env = None
  template = None

  if source:
    # Load jinja2 library.
    if options.jinja2:
      jinja2_path = os.path.normpath(options.jinja2)
    else:
      jinja2_path = os.path.normpath(
          os.path.join(os.path.abspath(__file__),
                       '../../../../third_party/jinja2'))
    sys.path.append(os.path.split(jinja2_path)[0])
    from jinja2 import Environment, FileSystemLoader

    # Create jinja2 environment.
    (template_path, template_name) = os.path.split(source)
    env = Environment(loader=FileSystemLoader(template_path),
                      extensions=['jinja2.ext.do', 'jinja2.ext.i18n'])

    # Register custom filters.
    env.filters['GetCodepage'] = GetCodepage
    env.filters['GetCodepageDecimal'] = GetCodepageDecimal
    env.filters['GetLangId'] = GetLangId
    env.filters['GetPrimaryLanguage'] = GetPrimaryLanguage
    env.filters['GetSublanguage'] = GetSublanguage

    # Register the message map with jinja2.i18n extension.
    env.globals['IsRtlLanguage'] = IsRtlLanguage
    env.globals['SelectLanguage'] = message_map.MakeSelectLanguage()
    env.install_gettext_callables(message_map.MakeGetText(),
                                  message_map.MakeGetText());

    template = env.get_template(template_name)

  # Generate a separate file per each locale if requested.
  outputs = []
  if options.locale_output:
    target = GypTemplate(options.locale_output)
    for lang in languages:
      context['languages'] = [ lang ]
      context['language'] = lang
      context['pak_suffix'] = GetDataPackageSuffix(lang)
      context['json_suffix'] = GetJsonSuffix(lang)
      message_map.SelectLanguage(lang)

      template_file_name = target.safe_substitute(context)
      outputs.append(template_file_name)
      if not options.print_only:
        WriteIfChanged(template_file_name, template.render(context),
                       options.encoding)
  else:
    outputs.append(options.output)
    if not options.print_only:
      WriteIfChanged(options.output, template.render(context), options.encoding)

  if options.print_only:
    # Quote each element so filename spaces don't mess up gyp's attempt to parse
    # it into a list.
    return " ".join(['"%s"' % x for x in outputs])

  return
Example #48
0
##     (at your option) any later version.

##     This program is distributed in the hope that it will be useful,
##     but WITHOUT ANY WARRANTY; without even the implied warranty of
##     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##     GNU Affero General Public License for more details.

##     You should have received a copy of the GNU Affero General Public License
##     along with this program.  If not, see <http://www.gnu.org/licenses/>.

'''
This module contains the html templates used in the GUI results. The reason 
that we don't separate them in independent files, is to avoid the headache of 
including separated files in packaging.
'''

import os
import codecs
from jinja2 import Template, Environment
from PySide import QtCore
from gettext import gettext, ngettext

env = Environment(extensions=['jinja2.ext.i18n'])
## use QT translator 
#env.install_gettext_callables(QtCore.QCoreApplication.translate, QtCore.QCoreApplication.translate, newstyle=False)
## use gettext
env.install_gettext_callables(gettext, ngettext)

base_path =  os.path.dirname( __file__ ) 
AYA_RESULTS_TEMPLATE = env.from_string(codecs.open(base_path + "/templates/aya_results.html","r", "utf-8").read())
TRANSLATION_RESULTS_TEMPLATE = env.from_string(codecs.open(base_path + "/templates/translation_results.html","r", "utf-8").read())
Example #49
0
class TemplateManager(object):
    """
    Uses to generate HTML page from template using Jinja2 templating.
    """

    def __init__(self):

        loader = ChoiceLoader([
            PackageLoader('rdiffweb', 'templates')
        ])

        # Load all the templates from /templates directory
        self.jinja_env = Environment(
            loader=loader,
            auto_reload=True,
            autoescape=True,
            extensions=[
                'jinja2.ext.i18n',
                'jinja2.ext.with_',
                'jinja2.ext.autoescape',
            ])

        # Register filters
        self.jinja_env.filters['filter'] = do_filter
        self.jinja_env.filters['datetime'] = do_format_datetime
        self.jinja_env.filters['filesize'] = do_format_filesize

        # Register method
        self.jinja_env.globals['attrib'] = attrib
        self.jinja_env.globals['url_for_browse'] = url_for_browse
        self.jinja_env.globals['url_for_history'] = url_for_history
        self.jinja_env.globals['url_for_restore'] = url_for_restore
        self.jinja_env.globals['url_for_settings'] = url_for_settings
        self.jinja_env.globals['url_for_status_entry'] = url_for_status_entry
        self.jinja_env.globals['load_translation'] = _get_translation
        self.jinja_env.globals['get_translation'] = _get_translation

    def add_templatesdir(self, templates_dir):
        """
        Add a new templates directory.
        """
        # Add a new template location to the list of loaders.
        loaders = self.jinja_env.loader.loaders
        loaders.append(FileSystemLoader(templates_dir))

    def compile_template(self, template_name, **kwargs):
        """Very simple implementation to render template using jinja2.
            `templateName`
                The filename to be used as template.
            `kwargs`
                The arguments to be passed to the template.
        """
        logger.log(1, "compiling template [%s]", template_name)
        self.jinja_env.install_gettext_callables(
            i18n.ugettext, i18n.ungettext, newstyle=True)
        template = self.jinja_env.get_template(template_name)
        data = template.render(kwargs)
        logger.log(1, "template [%s] compiled", template_name)
        return data

    def get_template(self, template_name):
        """
        Return a reference to the given template identify by `template_name`.
        This method is commonly used by plugins. If the `template_name` is not
        found an error is raised.
        """
        # Simply use the jinja env to return reference to template.
        return self.jinja_env.get_template(template_name)
Example #50
0
def Localize(source, locales, options):
    # Set the list of languages to use.
    languages = map(NormalizeLanguageCode, locales)
    # Remove duplicates.
    languages = sorted(set(languages))
    context = {'languages': languages}

    # Load the localized messages.
    message_map = MessageMap(languages, options.locale_dir)

    # Add OFFICIAL_BUILD variable the same way build/util/version.py
    # does.
    if os.environ.get('CHROME_BUILD_TYPE') == '_official':
        context['official_build'] = '1'
    else:
        context['official_build'] = '0'

    # Add all variables defined in the command line.
    if options.define:
        for define in options.define:
            context.update(dict([define.split('=', 1)]))

    # Read NAME=VALUE variables from file.
    if options.variables:
        for file_name in options.variables:
            ReadValuesFromFile(context, file_name)

    env = None
    template = None

    if source:
        # Load jinja2 library.
        if options.jinja2:
            jinja2_path = os.path.normpath(options.jinja2)
        else:
            jinja2_path = os.path.normpath(
                os.path.join(os.path.abspath(__file__),
                             '../../../../third_party/jinja2'))
        sys.path.append(os.path.split(jinja2_path)[0])
        from jinja2 import Environment, FileSystemLoader

        # Create jinja2 environment.
        (template_path, template_name) = os.path.split(source)
        env = Environment(loader=FileSystemLoader(template_path),
                          extensions=['jinja2.ext.do', 'jinja2.ext.i18n'])

        # Register custom filters.
        env.filters['GetCodepage'] = GetCodepage
        env.filters['GetCodepageDecimal'] = GetCodepageDecimal
        env.filters['GetLangId'] = GetLangId
        env.filters['GetPrimaryLanguage'] = GetPrimaryLanguage
        env.filters['GetSublanguage'] = GetSublanguage

        # Register the message map with jinja2.i18n extension.
        env.globals['IsRtlLanguage'] = IsRtlLanguage
        env.globals['SelectLanguage'] = message_map.MakeSelectLanguage()
        env.install_gettext_callables(message_map.MakeGetText(),
                                      message_map.MakeGetText())

        template = env.get_template(template_name)

    # Generate a separate file per each locale if requested.
    outputs = []
    if options.locale_output:
        target = GypTemplate(options.locale_output)
        for lang in languages:
            context['languages'] = [lang]
            context['language'] = lang
            context['pak_suffix'] = GetDataPackageSuffix(lang)
            context['json_suffix'] = GetJsonSuffix(lang)
            message_map.SelectLanguage(lang)

            template_file_name = target.safe_substitute(context)
            outputs.append(template_file_name)
            if not options.print_only and not options.locales_listfile:
                WriteIfChanged(template_file_name, template.render(context),
                               options.encoding)
    else:
        outputs.append(options.output)
        if not options.print_only:
            WriteIfChanged(options.output, template.render(context),
                           options.encoding)

    if options.print_only:
        # Quote each element so filename spaces don't mess up gyp's attempt to parse
        # it into a list.
        return " ".join(['"%s"' % x for x in outputs])

    if options.locales_listfile:
        # Strip off the quotes from each filename when writing into a listfile.
        content = u'\n'.join([x.strip('"') for x in outputs])
        WriteIfChanged(options.locales_listfile, content, options.encoding)

    return
Example #51
0
cli = parser.parse_args()


def guess_autoescape(template_name):
    if template_name is None or '.' not in template_name:
        return False
    ext = template_name.rsplit('.', 1)[1]
    return ext in ('html', 'htm', 'xml')

env = Environment(autoescape=guess_autoescape,
                  loader=FileSystemLoader(cli.templates),
                  extensions=['jinja2.ext.autoescape', 'jinja2.ext.i18n'])
env.install_gettext_callables(
    lambda x: get_translations().ugettext(x),
    lambda s, p, n: get_translations().ungettext(s, p, n),
    newstyle=True
)
            
def build():
    
    try:
        mappings, _ = parse_mapping(open(cli.babelconf))
    except IOError:
        sys.exit("Could not find Babel conf ({0})".format(cli.babelconf))
        
    search_paths = [search_path for (search_path, _) in mappings]
    
    def is_template(name):
        full_name = os.path.join(cli.templates, name)
        for path in search_paths:
Example #52
0
    def create(cls, config, app_globals):
        """Setup a renderer and loader for Jinja2 templates."""
        if jinja2 is None:  # pragma: no cover
            return None

        if config.get('use_dotted_templatenames', True):
            TemplateLoader = DottedTemplateLoader
            template_loader_args = {'dotted_finder': app_globals.dotted_filename_finder}
        else:
            TemplateLoader = FileSystemLoader
            template_loader_args = {}

        if not 'jinja_extensions' in config:
            config['jinja_extensions'] = []

        # Add i18n extension by default
        if not "jinja2.ext.i18n" in config['jinja_extensions']:
            config['jinja_extensions'].append("jinja2.ext.i18n")

        if not 'jinja_filters' in config:
            config['jinja_filters'] = {}

        loader = ChoiceLoader(
            [TemplateLoader(path, **template_loader_args) for path in config['paths']['templates']])

        jinja2_env = Environment(loader=loader, autoescape=True,
                                 auto_reload=config['auto_reload_templates'],
                                 extensions=config['jinja_extensions'])

        # Try to load custom filters module under app_package.lib.templatetools
        try:
            if not config['package_name']:
                raise AttributeError()

            filter_package = config['package_name'] + ".lib.templatetools"
            autoload_lib = __import__(filter_package, {}, {}, ['jinja_filters'])
            try:
                autoload_filters = dict(
                    map(lambda x: (x, autoload_lib.jinja_filters.__dict__[x]),
                                  autoload_lib.jinja_filters.__all__)
                )
            except AttributeError: #pragma: no cover
                autoload_filters = dict(
                    filter(lambda x: callable(x[1]),
                        autoload_lib.jinja_filters.__dict__.iteritems())
                )
        except (ImportError, AttributeError):
            autoload_filters = {}

        # Add jinja filters
        filters = dict(FILTERS, **autoload_filters)
        filters.update(config['jinja_filters'])
        jinja2_env.filters = filters

        # Jinja's unable to request c's attributes without strict_c
        config['tg.strict_tmpl_context'] = True

        # Add gettext functions to the jinja environment
        jinja2_env.install_gettext_callables(ugettext, ungettext)

        return {'jinja': cls(jinja2_env)}
Example #53
0
ureg = UnitRegistry()


def convertir(valor, unidad_inicial, unidad_final):
    if unidad_inicial == unidad_final:
        return valor
    valor *= ureg(unidad_inicial)
    return valor.to(unidad_final).magnitude


def unidad_html(unidad):
    return f'{ureg(unidad).units:~H}'


file_loader = FileSystemLoader(recursos.CARPETA_PLANTILLAS)
env = Environment(loader=file_loader, extensions=['jinja2.ext.i18n'])
env.globals.update(zip=zip, all=all)
env.install_gettext_callables(gettext.gettext, gettext.ngettext)
env.filters['convertir'] = convertir
env.filters['unidad_html'] = unidad_html

env.globals['SemanticCSS'] = os.path.join(recursos.CARPETA_CSS,
                                          'semantic.min.css')
env.globals['IconosCSS'] = os.path.join(recursos.CARPETA_CSS, 'icon.min.css')
env.globals['CustomCSS'] = os.path.join(recursos.CARPETA_CSS, 'custom.css')


def reporte(plantilla, **kwargs):
    plantilla_ = env.get_template(plantilla)
    return plantilla_.render(**kwargs)