我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用jinja2.ChoiceLoader()。
def __init__(self, templates_dir, openstack_release): if not os.path.isdir(templates_dir): log('Could not locate templates dir %s' % templates_dir, level=ERROR) raise OSConfigException self.templates_dir = templates_dir self.openstack_release = openstack_release self.templates = {} self._tmpl_env = None if None in [Environment, ChoiceLoader, FileSystemLoader]: # if this code is running, the object is created pre-install hook. # jinja2 shouldn't get touched until the module is reloaded on next # hook execution, with proper jinja2 bits successfully imported. apt_install('python-jinja2')
def __init__(self, templates_dir, openstack_release): if not os.path.isdir(templates_dir): log('Could not locate templates dir %s' % templates_dir, level=ERROR) raise OSConfigException self.templates_dir = templates_dir self.openstack_release = openstack_release self.templates = {} self._tmpl_env = None if None in [Environment, ChoiceLoader, FileSystemLoader]: # if this code is running, the object is created pre-install hook. # jinja2 shouldn't get touched until the module is reloaded on next # hook execution, with proper jinja2 bits successfully imported. if six.PY2: apt_install('python-jinja2') else: apt_install('python3-jinja2')
def register_template_dirs(self): """ Go Through all sub applications under (crm) and if a dir called (templates) found, register it as a template directory """ template_dirs = [] for root, dirs, _ in os.walk('crm'): for dir in dirs: if not dir == 'templates': continue template_dirs.append(os.path.abspath(os.path.join(root, dir))) template_loader = jinja2.ChoiceLoader([ self._app.jinja_loader, jinja2.FileSystemLoader(template_dirs), ] ) self._app.jinja_loader = template_loader
def init_blueprint(self, blueprint, path='templates.yaml'): """Initialize a Flask Blueprint, similar to init_app, but without the access to the application config. Keyword Arguments: blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None}) path {str} -- path to templates yaml file, relative to Blueprint (Default: {'templates.yaml'}) """ if self._route is not None: raise TypeError("route cannot be set when using blueprints!") # we need to tuck our reference to this Ask instance into the blueprint object and find it later! blueprint.ask = self # BlueprintSetupState.add_url_rule gets called underneath the covers and # concats the rule string, so we should set to an empty string to allow # Blueprint('blueprint_api', __name__, url_prefix="/ask") to result in # exposing the rule at "/ask" and not "/ask/". blueprint.add_url_rule("", view_func=self._flask_view_func, methods=['POST']) blueprint.jinja_loader = ChoiceLoader([YamlLoader(blueprint, path)])
def get_template_engine(self): engine = self.get('template_engine') if engine is None: templates = self['templates'] dirname = os.path.join(os.getcwd(), 'templates') if os.path.isdir(dirname): # pragma: no cover if dirname not in templates: templates.insert(0, dirname) elif os.getcwd() not in templates: templates.insert(0, os.getcwd()) loader = jinja2.ChoiceLoader([ FileSystemLoader(p) for p in templates ] + [jinja2.PackageLoader('nuka')]) self['template_engine'] = jinja2.Environment( loader=loader, undefined=jinja2.StrictUndefined, keep_trailing_newline=True, autoescape=False, ) return self['template_engine']
def test_render_loader(self, log, mkdir, fchown): with tempfile.NamedTemporaryFile() as fn1: context = { 'nats': { 'port': '1234', 'host': 'example.com', }, 'router': { 'domain': 'api.foo.com' }, 'nginx_port': 80, } template_loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(TEMPLATES_DIR)]) templating.render('fake_cc.yml', fn1.name, context, template_loader=template_loader) contents = open(fn1.name).read() self.assertRegexpMatches(contents, 'port: 1234') self.assertRegexpMatches(contents, 'host: example.com') self.assertRegexpMatches(contents, 'domain: api.foo.com')
def __init__(self, export_dir): self._export_dir = export_dir if os.path.exists(os.path.join(export_dir, 'theme')): shutil.rmtree(os.path.join(export_dir, 'theme')) shutil.copytree('theme', os.path.join(export_dir, 'theme')) self._env = Environment(loader=ChoiceLoader([ FileSystemLoader(os.path.join(export_dir, 'theme')), ])) self._env.filters['strftime'] = strftime self._env.filters['youtube_channel'] = youtube_channel self._env.filters['youtube_playlist'] = youtube_playlist self._env.filters['theme'] = self._theme
def configure(app): app.jinja_env.add_extension('jinja2.ext.do') app.jinja_env.add_extension('jinja2.ext.i18n') OVERLOAD_ENABLED = app.theme_context.get('OVERLOAD_ENABLED', True) TEMPLATES = Path('templates') THEME_FOLDER = Path(app.theme_context.get('FOLDER', 'themes')) ACTIVE_NAME = app.theme_context.get('ACTIVE', 'default') THEME_ACTIVE = Path(ACTIVE_NAME) THEME_TEMPLATE_FOLDER = THEME_FOLDER / THEME_ACTIVE / TEMPLATES PREFIXED = Path(f'pelican-{ACTIVE_NAME}') PREFIXED_TEMPLATE_FOLDER = THEME_FOLDER / PREFIXED / TEMPLATES THEME_STATIC_FOLDER = THEME_FOLDER / THEME_ACTIVE / Path('static') ABS_THEME_STATIC_FOLDER = Path.cwd() / THEME_STATIC_FOLDER DEFAULT_PATH = Path(app.jinja_loader.searchpath[0]) OVERLOAD_FOLDER = DEFAULT_PATH / f'overload_{THEME_ACTIVE}' / TEMPLATES FOLDERS = [THEME_TEMPLATE_FOLDER, PREFIXED_TEMPLATE_FOLDER] if OVERLOAD_ENABLED: FOLDERS.insert(0, OVERLOAD_FOLDER) my_loader = jinja2.ChoiceLoader([ QuokkaTemplateLoader(FOLDERS), app.jinja_loader ]) app.jinja_loader = my_loader @app.route('/theme/<path:filename>') def theme_static(filename): return send_from_directory(ABS_THEME_STATIC_FOLDER, filename)
def __init__(self, controller_or_app): self.app = controller_or_app.app if hasattr(controller_or_app, 'app') else controller_or_app self.env = jinja2.Environment( loader=jinja2.ChoiceLoader( ( jinja2.PackageLoader('pycommunicate'), jinja2.FileSystemLoader(self.app.template_directory) ) ) ) def add_includes(): return self.render_includes() self.env.globals.update({ 'add_includes': add_includes })
def jinja_render_file(path, lookup_paths=None): file_loaders = [jinja2.FileSystemLoader(os.path.dirname(path))] for p in lookup_paths: file_loaders.append(jinja2.FileSystemLoader(p)) env = jinja2.Environment(loader=jinja2.ChoiceLoader(loaders=file_loaders)) env.globals['address'] = address env.globals['raise_exception'] = j2raise env.filters['gethostbyname'] = socket.gethostbyname content = env.get_template(os.path.basename(path)).render(VARIABLES) return content
def initialize(self): super().initialize() # FIXME: Is this really the best way to use jinja2 here? # I can't seem to get the jinja2 env in the base handler to # actually load templates from arbitrary paths ugh. jinja2_env = self.settings['jinja2_env'] jinja2_env.loader = jinja2.ChoiceLoader([ jinja2_env.loader, jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__), 'templates') ) ])
def Template(app, path): loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(path), ]) app.jinja_loader = loader
def __init__(self, search_path: str, context: dict={}): loader = ChoiceLoader([ FileSystemLoader(search_path), PackageLoader('qface') ]) self.env = Environment( loader=loader, trim_blocks=True, lstrip_blocks=True ) self.env.filters.update(filters) self._destination = Path() self._source = '' self.context = context
def create_template_loader(self): template_roots = [] cls = self.__class__ while True: template_roots.append(os.path.dirname(inspect.getfile(cls))) cls = get_base_class(cls) if cls in (BaseIgnitionPackage, None): break return ChoiceLoader([FileSystemLoader(root) for root in template_roots])
def setup(app): procs = [request_processor] # setup Jinja2 template renderer app_loaders = [ jinja2.FileSystemLoader(os.path.join(settings.BASE_DIR, "app/views_min/")), jinja2.FileSystemLoader(os.path.join(settings.BASE_DIR, "app/views/")), jinja2.PackageLoader("aioweb", "views/") ] for app_name in settings.APPS: try: app_loaders.append(jinja2.PackageLoader(app_name, "app/views")) except ImportError as e: pass env = jinja2.Environment( loader=jinja2.ChoiceLoader(app_loaders), enable_async=True, trim_blocks=True, lstrip_blocks=True, extensions=[ DjangoStatic, DjangoUrl, DjangoNow, DjangoTrans ]) env.globals['settings'] = settings env.globals['app'] = app app[APP_KEY] = env app[APP_CONTEXT_PROCESSORS_KEY] = procs app.middlewares.append(context_processors_middleware) try: mod = importlib.import_module("app") setup = getattr(mod, 'setup_template') await awaitable(setup(env)) except (ImportError, AttributeError) as e: pass