def __init__(self, placeholder, *args, **kwargs):

        Environment.__init__(self, *args, **kwargs)
        self.placeholder = placeholder
        self.policies['json.dumps_kwargs'] = {
            'cls': Jinja2PlaceholderEncoder,
        }
Ejemplo n.º 2
0
 def __init__(self, placeholder, *args, **kwargs):
     Environment.__init__(self, *args, **kwargs)
     self.placeholder = placeholder
     filters = DefaultDict(lambda: (lambda _: ''))
     # pylint: disable=access-member-before-definition
     filters.update(self.filters)
     self.filters = filters
Ejemplo n.º 3
0
    def __init__(self, app: App):
        template_directory_paths = [
            join(path, 'templates') for path in app.assets.paths
        ]

        Environment.__init__(
            self,
            loader=FileSystemLoader(template_directory_paths),
            undefined=StrictUndefined,
            autoescape=select_autoescape(['html']),
            trim_blocks=True,
            extensions=[
                'jinja2.ext.do',
                'jinja2.ext.i18n',
            ],
        )

        self.app = app

        if app.configuration.mode == 'development':
            self.add_extension('jinja2.ext.debug')

        self._init_i18n()
        self._init_globals()
        self._init_filters()
        self._init_tests()
        self._init_extensions()
Ejemplo n.º 4
0
 def __init__(self, app, **options):
     if "loader" not in options:
         options["loader"] = app.create_global_jinja_loader()
     if "undefined" not in options:
         options["undefined"] = LoggingUndefined if app.debug else Undefined
     BaseEnvironment.__init__(self, **options)
     self.app = app
Ejemplo n.º 5
0
 def __init__(self, *args, **kw):
     kw['extensions'] = ('jinja2.ext.with_', )  # 启用with语句
     Environment.__init__(self, *args, **kw)
     # 把未定义变量和None处理为空字符串
     self.finalize = finalize
     self.undefined = MyUndefined
     self.filters.update(filters)
Ejemplo n.º 6
0
    def __init__(self):
        loaders = {}
        for resource in ctx.get_implementations(IResourceManager, instances=True):
            loaders[resource.resource_name] = FileSystemLoader(resource.templates_path)

        loader = ChoiceLoader([FileSystemLoader(ctx.cfg['templates.path']),
                               PrefixLoader(loaders)])

        cache_obj = None
        if ctx.cfg['templates.use_cache']:
            if ctx.cfg['templates.use_memcached_cache']:
                cache_obj = MemcachedBytecodeCache(
                    client=inyoka_cache,
                    timeout=ctx.cfg['caching.timeout']
                )
            elif ctx.cfg['templates.use_filesystem_cache']:
                cache_obj = FileSystemBytecodeCache(
                    directory=ctx.cfg['caching.filesystem_cache_path'],
                )

        Environment.__init__(self,
            loader=loader,
            extensions=['jinja2.ext.i18n', 'jinja2.ext.do', 'jinja2.ext.with_',
                        'jinja2.ext.autoescape'],
            auto_reload=ctx.cfg['templates.auto_reload'],
            undefined=StrictUndefined,
            cache_size=-1,
            bytecode_cache=cache_obj,
            autoescape=True
        )

        self.globals.update(
            INYOKA_REVISION=INYOKA_REVISION,
            PYTHON_VERSION='%d.%d.%d' % sys.version_info[:3],
            DEBUG=ctx.cfg['debug'],
            href=href,
        )
        self.filters.update(
            jsonencode=json.dumps,
            datetimeformat=l10n.format_datetime,
            dateformat=l10n.format_date,
            timeformat=l10n.format_time,
            timedelta=l10n.timedeltaformat,
            monthformat=l10n.format_month,
            dayformatshort=l10n.format_day_short,
            humanize=l10n.humanize_number,
        )
        self.install_gettext_translations(
            i18n.get_translations(),
            newstyle=True
        )
Ejemplo n.º 7
0
    def __init__(self):
        template_paths = list(settings.TEMPLATE_DIRS)

        template_paths.extend(glob(os.path.join(os.path.dirname(__file__),
                                                os.pardir, '*/templates')))
        loader = FileSystemLoader(template_paths)
        Environment.__init__(self, loader=loader,
                             extensions=['jinja2.ext.i18n', 'jinja2.ext.do'],
                             auto_reload=settings.DEBUG,
                             cache_size=-1)

        self.globals.update(url_for=url_for)

        self.install_gettext_translations(translation, newstyle=True)
Ejemplo n.º 8
0
    def __init__(self, *template_dirs):
        dirs = list(template_dirs)
        dirs += ['templates']
        Environment.__init__(self,
                             block_start_string='<#',
                             block_end_string='#>',
                             variable_start_string='<<',
                             variable_end_string='>>',
                             comment_start_string='<=',
                             comment_end_string='=>',
                             loader=FileSystemLoader(dirs))

        self.filters["f"] = filter_by_fstring
        self.filters["un"] = uncertain
        self.filters["n"] = nominal
        self.filters["escape"] = escape
        self.filters["unp"] = uncertain_parenthetical
Ejemplo n.º 9
0
    def init(self, layoutdir, cachedir):

        J2Environemnt.__init__(self,
            loader=ExtendedFileSystemLoader(layoutdir),
            bytecode_cache=FileSystemBytecodeCache(cachedir))

        # jinja2 is stupid and can't import any module during runtime
        import time, datetime, urllib

        for module in (time, datetime, urllib):
            self.globals[module.__name__] = module

            for name in dir(module):
                if name.startswith('_'):
                    continue
                obj = getattr(module, name)
                if hasattr(obj, '__class__') and callable(obj):
                    self.filters[module.__name__ + '.' + name] = obj
Ejemplo n.º 10
0
 def __init__(self, prefix_sep=":", *args, **kwargs):
   Environment.__init__(self, *args, **kwargs)
   self._prefix_sep = prefix_sep
Ejemplo n.º 11
0
 def __init__(self, app, **options):
     if 'loader' not in options:
         options['loader'] = app.create_global_jinja_loader()
     BaseEnvironment.__init__(self, **options)
     self.app = app
Ejemplo n.º 12
0
 def __init__(self, app: "Flask", **options: t.Any) -> None:
     if "loader" not in options:
         options["loader"] = app.create_global_jinja_loader()
     BaseEnvironment.__init__(self, **options)
     self.app = app
Ejemplo n.º 13
0
 def __init__(self, loader=None):
     Environment.__init__(self, loader=loader, enable_async=True)
     self.urlpaths = {}
     self.loader = loader
Ejemplo n.º 14
0
    def __init__(self, app, *args, **options):
        if 'loader' not in options:
            options['loader'] = app.createGlobalTemplateLoader()

        BaseEnvironment.__init__(self, *args, **options)
        self.app = app
Ejemplo n.º 15
0
    def __init__(self, app, *args, **options):
        if 'loader' not in options:
            options['loader'] = app.createGlobalTemplateLoader()

        BaseEnvironment.__init__(self, *args, **options)
        self.app = app
Ejemplo n.º 16
0
 def __init__(self, loader=None):
     Environment.__init__(self, loader=loader)
     self.urlpaths = {}
     self.loader = loader
Ejemplo n.º 17
0
			def __init__(self, prefix_sep=":", *args, **kwargs):
				Environment.__init__(self, *args, **kwargs)
				self._prefix_sep = prefix_sep
Ejemplo n.º 18
0
 def __init__(self, *args, **kw):
     Environment.__init__(self, *args, **kw)
     # 把未定义变量和None处理为空字符串
     self.finalize = finalize
     self.undefined = MyUndefined
     self.filters.update(filters)
Ejemplo n.º 19
0
 def __init__(self, *a, **kw):
     Jinja2Environment.__init__(self, *a, **kw)
     from django_assets.env import get_env
     self.assets_environment = get_env()
Ejemplo n.º 20
0
 def __init__(self, app, **options):
     if 'loader' not in options:
         options['loader'] = app.create_global_jinja_loader()
     BaseEnvironment.__init__(self, **options)
     self.app = app
Ejemplo n.º 21
0
    def __init__(self, site: Site):
        template_directory_paths = [
            join(path, 'templates') for path in site.assets.paths
        ]

        Environment.__init__(
            self,
            enable_async=True,
            loader=FileSystemLoader(template_directory_paths),
            undefined=StrictUndefined,
            autoescape=select_autoescape(['html']),
            trim_blocks=True,
            extensions=[
                'jinja2.ext.do',
                'jinja2.ext.i18n',
            ],
        )

        self.site = site

        if site.configuration.mode == 'development':
            self.add_extension('jinja2.ext.debug')

        def _gettext(*args, **kwargs):
            return gettext(*args, **kwargs)

        def _ngettext(*args, **kwargs):
            return ngettext(*args, **kwargs)

        self.install_gettext_callables(_gettext, _ngettext)
        self.policies['ext.i18n.trimmed'] = True
        self.globals['site'] = site
        self.globals['locale'] = site.locale
        today = datetime.date.today()
        self.globals['today'] = Date(today.year, today.month, today.day)
        self.globals['plugins'] = _Plugins(site.plugins)
        self.globals['urlparse'] = urlparse
        self.filters['map'] = _filter_map
        self.filters['flatten'] = _filter_flatten
        self.filters['walk'] = _filter_walk
        self.filters['selectwhile'] = _filter_selectwhile
        self.filters['locale_get_data'] = lambda locale: Locale.parse(
            locale, '-')
        self.filters['negotiate_localizeds'] = _filter_negotiate_localizeds
        self.filters['sort_localizeds'] = _filter_sort_localizeds
        self.filters['select_localizeds'] = _filter_select_localizeds
        self.filters['negotiate_dateds'] = _filter_negotiate_dateds
        self.filters['select_dateds'] = _filter_select_dateds

        # A filter to convert any value to JSON.
        @contextfilter
        def _filter_json(context, data, indent=None):
            return stdjson.dumps(data,
                                 indent=indent,
                                 cls=JSONEncoder.get_factory(
                                     site,
                                     resolve_or_missing(context, 'locale')))

        self.filters['json'] = _filter_json

        # Override Jinja2's built-in JSON filter, which escapes the JSON for use in HTML, to use Betty's own encoder.
        @contextfilter
        def _filter_tojson(context, data, indent=None):
            return htmlsafe_json_dumps(data,
                                       indent=indent,
                                       dumper=lambda *args, **kwargs:
                                       _filter_json(context, *args, **kwargs))

        self.filters['tojson'] = _filter_tojson
        self.tests['resource'] = lambda x: isinstance(x, Resource)

        def _build_test_resource_type(resource_type: Type[Resource]):
            def _test_resource(x):
                return isinstance(x, resource_type)

            return _test_resource

        for resource_type in RESOURCE_TYPES:
            self.tests[
                '%s_resource' %
                resource_type.resource_type_name] = _build_test_resource_type(
                    resource_type)
        self.tests['identifiable'] = lambda x: isinstance(x, Identifiable)
        self.tests['has_links'] = lambda x: isinstance(x, HasLinks)
        self.tests['has_files'] = lambda x: isinstance(x, HasFiles)
        self.tests['startswith'] = str.startswith
        self.tests['subject_role'] = lambda x: isinstance(x, Subject)
        self.tests['witness_role'] = lambda x: isinstance(x, Witness)
        self.tests['date_range'] = lambda x: isinstance(x, DateRange)
        self.filters['paragraphs'] = _filter_paragraphs

        @contextfilter
        def _filter_format_date(context, date: Datey):
            locale = resolve_or_missing(context, 'locale')
            return format_datey(date, locale)

        self.filters['format_date'] = _filter_format_date
        self.filters['format_degrees'] = _filter_format_degrees
        self.globals['citer'] = _Citer()

        @contextfilter
        def _filter_url(context,
                        resource,
                        media_type=None,
                        locale=None,
                        **kwargs):
            media_type = media_type if media_type else 'text/html'
            locale = locale if locale else resolve_or_missing(
                context, 'locale')
            return site.localized_url_generator.generate(resource,
                                                         media_type,
                                                         locale=locale,
                                                         **kwargs)

        self.filters['url'] = _filter_url
        self.filters['static_url'] = site.static_url_generator.generate
        self.filters['file'] = lambda *args: _filter_file(site, *args)
        self.filters['image'] = lambda *args, **kwargs: _filter_image(
            site, *args, **kwargs)
        self.globals['search_index'] = lambda: Index(site).build()
        self.globals['html_providers'] = list([
            plugin for plugin in site.plugins.values()
            if isinstance(plugin, HtmlProvider)
        ])
        self.globals['path'] = os.path
        for plugin in site.plugins.values():
            if isinstance(plugin, Jinja2Provider):
                self.globals.update(plugin.globals)
                self.filters.update(plugin.filters)