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 create_blueprint(self, admin): res = super(OpenERPModelView, self).create_blueprint(admin) loader = ChoiceLoader([ PackageLoader('flask_admin_openerp'), self.blueprint.jinja_loader ]) self.blueprint.jinja_loader = loader return res
def __init__(self, loader: BaseLoader = None): self._loader = ChoiceLoader(loaders=[]) if loader is None: # Use a default FileSystemLoader. self._loader.loaders.append( FileSystemLoader(searchpath="templates")) self._environment = None
def jinja_loader(self): if self.template_folder is not None: loaders = [ FileSystemLoader( path.join(self.root_path, self.template_folder)) ] else: loaders = [] return ChoiceLoader(loaders)
def __init__(self, dbtype): loaders = [PackageLoader('dwgenerator', f'sql/{dbtype}')] # Use standard SQL as fallback if not the specific template is implemented. if dbtype != 'standard': loaders.append(PackageLoader('dwgenerator', 'sql/standard')) self.env = Environment( loader=ChoiceLoader(loaders), trim_blocks=True, lstrip_blocks=True, )
def __getattr__(self, name): if self._environment == None: self._environment = Environment(extensions=global_exts, loader=ChoiceLoader(loader_array)) self._environment.globals['STATIC_URL'] = settings.STATIC_URL self._environment.globals['url_reverse'] = get_callable( 'django.core.urlresolvers.reverse_lazy') if name == '__members__': return dir(self._environment) return getattr(self._environment, name)
def __getattr__(self, name): if self._environment == None: self._environment = Environment(extensions=global_exts, loader=ChoiceLoader(loader_array)) self._environment.block_start_string = '((*' self._environment.block_end_string = '*))' self._environment.variable_start_string = '(((' self._environment.variable_end_string = ')))' self._environment.comment_start_string = '((=' self._environment.comment_end_string = '=))' self._environment.filters['escape_tex'] = escape_tex if name == '__members__': return dir(self._environment) return getattr(self._environment, name)
def JINJA_ENV(self): from engineer.filters import format_datetime, markdown_filter, localtime, naturaltime, compress from engineer.processors import preprocess_less from engineer.themes import ThemeManager # Configure Jinja2 environment logger.debug("Configuring the Jinja environment.") # Helper function to look up a URL by name def urlname(name, *args): url = settings.URLS.get(name, settings.HOME_URL) if isfunction(url): return url(*args) else: return url env = Environment( loader=ChoiceLoader([ FileSystemLoader([self.TEMPLATE_DIR]), ThemeManager.current_theme().template_loader, #self.ENGINEER.THEMES_DIR / 'base_templates', FileSystemLoader([self.ENGINEER.TEMPLATE_DIR]) ]), extensions=[ 'jinja2.ext.with_', ], #'compressinja.html.HtmlCompressor'], bytecode_cache=FileSystemBytecodeCache( directory=self.JINJA_CACHE_DIR), trim_blocks=True) # Filters env.filters['compress'] = compress env.filters['date'] = format_datetime env.filters['localtime'] = localtime env.filters['naturaltime'] = naturaltime env.filters['markdown'] = markdown_filter env.filters['typogrify_no_widont'] = typogrify_no_widont register(env) # register typogrify filters # Globals env.globals['theme'] = ThemeManager.current_theme() env.globals['urlname'] = urlname env.globals['preprocess_less'] = preprocess_less # env.globals['url'] = url env.globals['STATIC_URL'] = self.STATIC_URL env.globals['DEBUG'] = self.DEBUG env.globals['settings'] = self return env
def make_jinja_loader(self): template_path = os.path.join(config.basedir, self.path, "templates") default_jinja_loader = DefaultTheme.make_jinja_loader() prefix_default_loader = PrefixLoader( {"mediatum": default_jinja_loader}) if os.path.isdir(template_path): # This loader first looks # at the CustomTheme template path, then the default template path, if nothing was found. return ChoiceLoader([ prefix_default_loader, FileSystemLoader(template_path), default_jinja_loader ]) else: # no template dir for this theme, only use templates from default theme return default_jinja_loader
def get_template(self, context, modname, filename): """ Render a single template. :param context: :param modname: :param filename: :return: """ from jinja2 import Environment, PackageLoader from jinja2.loaders import ChoiceLoader dirname, filename = filename.rsplit('/', 1) loader = ChoiceLoader([ PackageLoader('starterpyth', 'templates'), PackageLoader(modname, dirname) ]) env = Environment(loader=loader) template = env.get_template(filename) return template.render(**context)
def init_app(self, app: Flask, route: Optional[str] = None, templates_file: Optional[str] = None) -> None: """Initialize a Flask app. This can be used to manually initialize a Flask app when it wasn't passed to init. Adds the route, the template loader and a shell context processor. Sets auto_reload to True on the Jinja env. Args: app: The Flask app to initialize with this agent. route: The URL endpoint for this agent. If None, defaults to the agents route. templates_file: The YAML templates file. If None, defaults to the agents template file. Returns: None """ app.add_url_rule( route or self.route, view_func=self._flask_view_func, methods=['POST'], ) # Add the YamlLoader, but keep the original one templates_file = templates_file or self.templates_file templates_path = os.path.join(app.root_path, templates_file) app.jinja_loader = ChoiceLoader( [app.jinja_loader, YamlLoaderWithRandomization(templates_path)]) app.jinja_env.auto_reload = True # Store a reference to the agent so that we can refer to it from an # app context if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['flask_dialogflow'] = self # Make the agent available in a flask shell app.shell_context_processor(self._flask_shell_context_processor)
def __init__(self, root_dir, ops_config): loader = ChoiceLoader( [FileSystemLoader(root_dir), FileSystemLoader("/")]) mode = ops_config.get('jinja2.undefined') undefined = Undefined if mode == 'StrictUndefined': undefined = StrictUndefined elif mode == 'DebugUndefined': undefined = DebugUndefined self.env = Environment(loader=loader, undefined=undefined) self.filter_plugin_loader = PluginLoader( 'FilterModule', 'ansible.plugins.filter', ops_config.ansible_filter_plugins.split(':'), 'filter_plugins') for filter in self.filter_plugin_loader.all(): self.env.filters.update(filter.filters())
def write_files(self, context, filters): """ Write template or raw files to the new project :param context: context (dict) to be used by jinja2 :param filters: extra filters for jinja2 :param excludes: files to exclude :return: """ from jinja2 import Environment, PackageLoader, Template from jinja2.loaders import ChoiceLoader local_context = copy.copy(context) local_context.update(self.get_local_context(local_context)) excludes = self.get_excluded_files(local_context) modname, dirname = self.get_resources() if modname is None or dirname is None: return loader = ChoiceLoader([ PackageLoader('starterpyth', 'templates'), PackageLoader(modname, dirname) ]) env = Environment(loader=loader) env.filters.update(filters) project_root = os.path.join(context['project_root'], context['project_name']) if not os.path.isdir(project_root): msg = _('Directory %(f)s created.') % {'f': project_root} logging.info(msg) os.makedirs(project_root) # noinspection PyTypeChecker prefix_len = len(dirname) + 1 def get_path(root, name): """return relative source path (to template dir) and destination path""" src_path = (root + '/' + name)[prefix_len:] dst_path = src_path if os.sep != '/': dst_path = dst_path.replace('/', os.sep) if dst_path.find('{') > -1: dst_path = Template(dst_path).render(**local_context) if dst_path[-4:] == '_tpl': dst_path = dst_path[:-4] return src_path, os.path.join(project_root, dst_path) for root, dirnames, filenames in starterpyth.utils.walk( modname, dirname): for dirname in dirnames: src_path, dst_path = get_path(root, dirname) if src_path in excludes: continue if not os.path.isdir(dst_path): msg = _('Directory %(f)s created.') % {'f': dst_path} logging.info(msg) os.makedirs(dst_path) for filename in filenames: if filename[-4:] == '_inc': continue src_path, dst_path = get_path(root, filename) if src_path in excludes: continue if not os.path.isdir(os.path.dirname(dst_path)): continue if filename[-4:] == '_tpl': template = env.get_template(src_path) f_out = open(dst_path, 'ab') f_out.write( template.render(**local_context).encode('utf-8')) f_out.close() msg = _('Template %(f)s written.') % {'f': dst_path} logging.info(msg) else: f_out = open(dst_path, 'wb') f_in = pkg_resources.resource_stream( modname, root + '/' + filename) data = f_in.read(10240) while data: f_out.write(data) data = f_in.read(10240) f_in.close() f_out.close() msg = _('File %(f)s written.') % {'f': dst_path} logging.info(msg)
def jinja_loader(self): if self.template_folder is not None: return ChoiceLoader([BlohgLoader(self.template_folder), super(_Flask, self).jinja_loader])
# [email protected] # # ============================================================================ """ A default Jinja2 environment for the rendering of html in print previews and others. The `loader` loads its templates from the camelot/art/templates folder. As it is a :class:`jinja2.loaders.ChoiceLoader` object, other loaders can be appended or prepended to it :attr:`loaders` attribute, to customize the look of the print previews or reuse the existing style The `environment` is a :class:`jinja2.environment.Environment` which uses the `loader` and that can be used with the :class:`camelot.view.action_steps.print_preview.PrintJinjaTemplate` action step. """ from jinja2.environment import Environment from jinja2.loaders import ChoiceLoader, PackageLoader loader = ChoiceLoader([PackageLoader('camelot.art')]) class DefaultEnvironment(Environment): def __repr__(self): return '<camelot.core.templates.environment>' environment = DefaultEnvironment(loader=loader)