我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用jinja2.StrictUndefined()。
def main(args=sys.argv[1:]): acls, groups, aliases = process_acls(make_well_known_acls()) env = Environment( loader=FileSystemLoader(os.getcwd()), undefined=StrictUndefined, trim_blocks=True, ) env.filters['slugify'] = slugify_filter template = env.get_template(args[0]) values = dict( acls=acls, aliases=aliases, groups=groups, version=__version__, ) print(template.render(**values))
def interpolate_value(value: str, context: dict): """Expand Jinja templating in the definitions.""" if type(value) == str and "{{" in value: t = jinja2.Template(value, undefined=jinja2.StrictUndefined) try: v = t.render(**context) except jinja2.exceptions.TemplateError as e: raise RuntimeError("Could not expand template value: {}".format(value)) from e # Jinja template rendering does not have explicit int support, # so we have this hack in place try: v = int(v) except ValueError: pass return v else: return value
def jinja_render(path, context, functions=(), ignore_undefined=False): kwargs = {} if ignore_undefined: kwargs['undefined'] = SilentUndefined else: kwargs['undefined'] = jinja2.StrictUndefined env = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(path)), **kwargs) env.filters['host'] = get_host # FIXME: gethostbyname should be only used during config files render env.filters['gethostbyname'] = lambda x: x for func in functions: env.globals[func.__name__] = func env.globals['raise_exception'] = j2raise content = env.get_template(os.path.basename(path)).render(context) return content
def _generate_pages(html_path, css_names, js_names): env = jinja2.Environment( undefined=jinja2.StrictUndefined, loader = jinja2.FileSystemLoader(html_path), lstrip_blocks=True, trim_blocks=True, ) pages = { 'Bank Wrangler': 'index.html', 'List': 'list.html', 'Balance': 'balance.html', 'Spending': 'spending.html', } # used by base.html env.globals = { 'cssimports': css_names, 'jsimports': js_names, 'pages': [{'name': title, 'url': filename} for title, filename in pages.items()], } return {filename: env.get_template(filename).render(selectedpage=filename) for filename in pages.values()}
def _get_rendered_template(self, template_name): template_dir_path = os.path.abspath(os.path.join( self._template_path, self._preset, )) template_loader = jinja2.FileSystemLoader( searchpath=template_dir_path, ) template_env = jinja2.Environment( loader=template_loader, undefined=jinja2.StrictUndefined, trim_blocks=True, ) template = template_env.get_template(template_name + '.j2') try: rendered_template = template.render(self._config) except jinja2.exceptions.UndefinedError as err: raise YamlRstReformatterError( "{}. Consider providing the variable as config option.".format(err) ) return rendered_template
def __init__(self, *, context_name, filetype, output_filetype=None, jinja_options, replacements): self.base_template = config.BASE_FILE_NAME self.context_name = context_name self.filetype = filetype self.output_filetype = output_filetype self.replacements = replacements self.username = None context_templates_dir = posixpath.join(config.TEMPLATES_DIR, context_name) jinja_options = jinja_options.copy() jinja_options["loader"] = jinja2.FileSystemLoader( searchpath=context_templates_dir ) jinja_options["undefined"] = jinja2.StrictUndefined self.jinja_env = jinja2.Environment(**jinja_options) self.known_section_types = [os.path.splitext(os.path.basename(s))[0] for s in files_of_type( self.filetype, posixpath.join(context_templates_dir, config.SECTIONS_DIR))]
def render_k8s_resource(file_name, variables): """Render k8s resource files using jinga2. Args: file_name: A filename string for the yaml template version: Version string will be used as the jinja version variable tag: Image tag string will be used as a jinga imagetag variable Returns: Rendered resource dict """ with open(file_name, 'r') as deploy_file: deploy_string = deploy_file.read() deploy_template = jinja2.Template(deploy_string) deploy_template.environment.undefined = jinja2.StrictUndefined deploy_string = deploy_template.render(variables) return yaml.load(deploy_string)
def _render_jinja_template(template_dir, filename, jinja_vars): """ Renders a jinja template. Sceptre supports passing sceptre_user_data to JSON and YAML CloudFormation templates using Jinja2 templating. :param template_dir: The directory containing the template. :type template_dir: str :param filename: The name of the template file. :type filename: str :param jinja_vars: Dict of variables to render into the template. :type jinja_vars: dict :returns: The body of the CloudFormation template. :rtype: string """ logger = logging.getLogger(__name__) logger.debug("%s Rendering CloudFormation template", filename) env = jinja2.Environment( loader=jinja2.FileSystemLoader(template_dir), undefined=jinja2.StrictUndefined ) template = env.get_template(filename) body = template.render(**jinja_vars) return body
def render(templates_dir, template, context, context_overrides={}): ''' Render a job XML from job definition. If *insert_hash* is true, also include a hash of the configuration as text in the job description. :param templates_dir: location of the jobs templates :param template: the path to the job template, relative to *templates_dir* :param context: a dict containing the variables passed to the tamplate :param context_overrides: a mapping that will be deep merged in the final context :return: a ``(rendered_template, template_files)`` tuple, where ``template_files`` is the set of files that were loaded to render the template ''' loader = TrackingFileSystemLoader(templates_dir) env = jinja2.Environment(loader=loader, autoescape=True, undefined=jinja2.StrictUndefined) template = env.get_template(template) context = utils.deep_merge(context, context_overrides) return template.render(**context), loader.loaded_files
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 debug_app(app): """Add the debug toolbar extension to the application.""" app.jinja_env.undefined = jinja2.StrictUndefined try: import flask_debugtoolbar except ImportError: flask_debugtoolbar = None else: app.config['SECRET_KEY'] = 'debug-secret-key' flask_debugtoolbar.DebugToolbarExtension(app)
def render_from_string(string, context): environment = Environment(undefined=StrictUndefined) return environment.from_string(string).render(**context)
def render_jinja(dict_, template_str): """Render dict onto jinja template and return the string result""" name = 'jvars' j2env = jinja2.Environment( loader=jinja2.DictLoader({ name: template_str }), undefined=jinja2.StrictUndefined, extensions=["jinja2.ext.do"]) # Add some custom jinja filters j2env.filters['bool'] = TypeUtils.str_to_bool j2env.filters['yaml'] = YamlUtils.yaml_dict_to_string j2env.filters['base64encode'] = base64.b64encode # Add a "raise" keyword for raising exceptions from within jinja j2env.globals['raise'] = JinjaUtils._jinja_keyword_raise j2env.globals['gen_names'] = JinjaUtils._jinja_keyword_gen_names j2env.globals['mkpass'] = JinjaUtils.mkpass j2env.globals['keygen'] = JinjaUtils.keygen j2env.globals['self_signed_cert_gen'] = JinjaUtils.self_signed_cert_gen j2env.globals['ceph_key'] = JinjaUtils.ceph_key j2env.globals['uuid'] = JinjaUtils.uuid # Render the template rendered_template = j2env.get_template(name).render(dict_) return rendered_template + "\n"
def _build_env(): # Ignore bandit false positive: B701:jinja2_autoescape_false # This env is not used to render content that is vulnerable to XSS. env = jinja2.Environment( # nosec loader=jinja2.PackageLoader('promenade', 'templates/include'), undefined=jinja2.StrictUndefined) env.filters['b64enc'] = _base64_encode env.filters['fill_no_proxy'] = _fill_no_proxy env.filters['yaml_safe_dump_all'] = _yaml_safe_dump_all return env
def __getitem__(self, path): value = self.get_path(path) if value: return value else: return jinja2.StrictUndefined('No match found for path %s' % path)
def get_first(self, *paths): result = self._get_first(*paths) if result: return result else: return jinja2.StrictUndefined( 'Nothing found matching paths: %s' % ','.join(paths))
def get(self, *, kind=None, name=None, schema=None): result = _get(self.documents, kind=kind, schema=schema, name=name) if result: return result['data'] else: return jinja2.StrictUndefined( 'No document found matching kind=%s schema=%s name=%s' % (kind, schema, name))
def kubelet_name(self): for document in self.iterate(kind='Genesis'): return 'genesis' for document in self.iterate(kind='KubernetesNode'): return document['data']['hostname'] return jinja2.StrictUndefined( 'No Genesis or KubernetesNode found while getting kubelet name')
def getOptions(): try: options, args = getopt.getopt(sys.argv[1:], "y:j:n:sw", ["yaml=", "jinja=", "notrim", "strict", "warning"]) except getopt.GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" sys.exit(2) global yamlfile,jinjafile,trim,undefined trim = True opts = 0 for opt,arg in options: opts = opts + 1 if opt in ("-y","-yaml"): yamlfile = arg elif opt in ("-j","-jinja"): jinjafile = arg elif opt in ("-n","-notrim"): trim = False elif opt in ("-w","-warning"): undefined = make_logging_undefined (base = Undefined) elif opt in ("-s","-strict"): undefined = make_logging_undefined (base = StrictUndefined) return opts > 0
def render(template_file, **kwargs): env = Environment(loader=FileSystemLoader(BASE_PATH), trim_blocks=True, undefined=StrictUndefined) jinja_filters = { "to_yaml": lambda obj: yaml.dump(obj, default_flow_style=False), "indent": indent_text, } env.filters.update(jinja_filters) template = env.get_template(template_file) return template.render(**kwargs)
def render(template_file, **kwargs): env = Environment(loader=FileSystemLoader(BASE_PATH), trim_blocks=True, undefined=StrictUndefined) jinja_filters = { "to_yaml": lambda obj: yaml.dump(obj, default_flow_style=False), "indent": indent_text, "is_root_model": is_root_model, } env.filters.update(jinja_filters) template = env.get_template(template_file) return template.render(**kwargs)
def template(string, **kwargs): env = jinja2.Environment( undefined=jinja2.StrictUndefined, extensions=['jinja2.ext.do'], keep_trailing_newline=True, ) env.filters.update(jinja_filters.load_filters()) template = env.from_string(string) return template.render(**kwargs)
def _make_environment(load, additionals, extensions): extensions.append(ext.with_) env = jinja2.Environment( loader=jinja2.FunctionLoader(load), undefined=jinja2.StrictUndefined, trim_blocks=True, lstrip_blocks=True, extensions=extensions, ) for name, defs in additionals.items(): getattr(env, name).update(defs) return env
def render(tpl_path, context): fpath, filename = path.split(tpl_path) env = Environment(loader=FileSystemLoader(fpath or './'), undefined=StrictUndefined) tmp = env.get_template(filename) return tmp.render(context)
def render_config(self, config): """Render service config using jinja.""" config_template = jinja2.Template(str(config)) config_template.environment.undefined = jinja2.StrictUndefined config_string = config_template.render(self.variables) return yaml.load(config_string)
def get_env(self, extensions = None): default_extensions = [ "jinja2.ext.do", "jinja2.ext.with_" ] if extensions: extensions.extend(default_extensions) else: extensions = default_extensions kwargs = dict(trim_blocks = True, lstrip_blocks = True, undefined = StrictUndefined, extensions = extensions) #if not template_path.startswith("/"): kwargs["loader"] = PackageLoader("onering", "data/templates") env = Environment(**kwargs) env.loader = self return env
def _read(self, directory_path, basename): """ Traverses the directory_path, from top to bottom, reading in all relevant config files. If config items appear in files lower down the environment tree, they overwrite items from further up. :param directory_path: Relative directory path to config to read. :type directory_path: str :param filename: Base config to provide defaults. :type filename: dict :returns: Representation of inherited config. :rtype: dict """ abs_directory_path = path.join(self.config_folder, directory_path) if path.isfile(path.join(abs_directory_path, basename)): env = jinja2.Environment( loader=jinja2.FileSystemLoader(abs_directory_path), undefined=jinja2.StrictUndefined ) template = env.get_template(basename) rendered_template = template.render( environment_variable=environ, environment_path=directory_path.split("/"), **self.templating_vars ) config = yaml.safe_load(rendered_template) return config
def _get_template_engine(ctx): """ Initialize the template engine environment """ global engine_cache if engine_cache is not None: return engine_cache loader_map = {} loader_map[""] = FileSystemLoader(os.path.join(Project.get().project_path, "templates")) for name, module in Project.get().modules.items(): template_dir = os.path.join(module._path, "templates") if os.path.isdir(template_dir): loader_map[name] = FileSystemLoader(template_dir) # init the environment env = Environment(loader=PrefixLoader(loader_map), undefined=jinja2.StrictUndefined) env.context_class = ResolverContext # register all plugins as filters for name, cls in ctx.get_compiler().get_plugins().items(): def curywrapper(func): def safewrapper(*args): return JinjaDynamicProxy.return_value(func(*args)) return safewrapper env.filters[name.replace("::", ".")] = curywrapper(cls) engine_cache = env return env
def render_from_file(path, template, **kwargs): env = Environment(loader=FileSystemLoader(path), undefined=StrictUndefined, trim_blocks=True) # env.filters.update(jinja_filters.filters()) template = env.get_template(template) return template.render(**kwargs)
def render_from_string(template, **kwargs): env = Environment(undefined=StrictUndefined, trim_blocks=True) template = env.from_string(template) return template.render(**kwargs)
def generate_wiki(self, data, wiki_template): """generates wiki file based on data file and wiki template""" env = Environment(loader=FileSystemLoader(TEMPLATES_PATH), undefined=StrictUndefined, trim_blocks=True) for b in data.get('builds', []): b['issues'] = convert_bugs_to_links(b['issues']) template = env.get_template(wiki_template) return template.render(**data)
def get_parsed_lines(self): ''' Returns a set of lines with all variables filed in ''' try: return Template(self.profile, undefined=StrictUndefined).render(self.variables) except UndefinedError as e: raise Exception(e)
def build(staticdatadir, outdir, templatedir, input_file): try: shutil.rmtree(outdir) except Exception: pass os.makedirs(outdir) data = {ident: load_data(os.path.join(staticdatadir, filename)) for ident, filename in STATIC_DATA_FILES.items()} data['schema'] = registered_properties data['results'] = results = {} for filename in input_file: result = load_data(filename) try: result = dict(result) except ValueError: raise ValueError('Data needs to be a mapping: ', filename) if not set(result.keys()).isdisjoint(results.keys()): raise ValueError('Overwriting data: ', filename) results.update(result) loader = jinja2.FileSystemLoader(templatedir) template_env = jinja2.Environment( loader=loader, undefined=jinja2.StrictUndefined, ) def render(out_name, template_name, **env): template = template_env.get_template(template_name) result = template.render(data=data, **env) output_filename = os.path.join(outdir, out_name) dirname = os.path.dirname(output_filename) try: os.makedirs(dirname) except OSError: pass print('Writing:', output_filename) with open(output_filename, 'w') as file: file.write(result) # Render all the pages render('index.html', 'index.html', breadcrumbs=()) for name, testcase in data['results'].items(): render('cases/{}.html'.format(name), 'testcase.html', testcase_name=name, testcase=testcase, breadcrumbs=[ ('Network Test Report', '../index.html'), (name, None), ]) print('Wrote to', os.path.abspath(outdir))
def _template(self, filename, filters=None, alternate_marking=False): """ Open a template file """ def filter_wordwrap(value, width=79): return '\n\n'.join([textwrap.fill(str, width) for str in value.split('\n\n')]) def filter_indent(value, level=0, prefix=""): return ('\n' + '\t' * level + prefix).join(value.split('\n')) def global_abort_helper(msg): raise BuilderException(msg) if filename.startswith('#'): name = filename[1:] loader = jinja2.PackageLoader('pando', 'resources') else: # if not os.path.isabs(filename): # relpath = os.path.dirname(os.path.abspath(__file__)) # path = os.path.join(relpath, path) path = os.path.dirname(filename) name = os.path.basename(filename) loader = jinja2.FileSystemLoader(path) if alternate_marking: environment = jinja2.Environment( block_start_string='<%', block_end_string='%>', variable_start_string='<<', variable_end_string='>>', comment_start_string='<#', comment_end_string='#>', line_statement_prefix='##', line_comment_prefix='###', loader=loader, undefined=jinja2.StrictUndefined, extensions=["jinja2.ext.loopcontrols"]) else: environment = jinja2.Environment( line_statement_prefix='##', line_comment_prefix='###', loader=loader, undefined=jinja2.StrictUndefined, extensions=["jinja2.ext.loopcontrols"]) environment.filters['xpcc.wordwrap'] = filter_wordwrap environment.filters['xpcc.indent'] = filter_indent environment.globals['abort'] = global_abort_helper if filters: environment.filters.update(filters) template = environment.get_template(name, globals=self.globals) return template
def render_template(self, name_or_statement, context=None, by_name=False): if by_name: if name_or_statement not in self._templates: raise ValueError("No such template of name: '{}'.".format(name_or_statement)) statement = self._templates[name_or_statement] else: statement = name_or_statement try: from sqlalchemy.sql.base import Executable if isinstance(statement, Executable): statement = str(statement.compile(compile_kwargs={"literal_binds": True})) except ImportError: pass if context is None or context is False: context = {} template_context = {} template_context.update(self._template_context) # default context template_context.update(context) # context passed in intersection = set(self._template_context.keys()) & set(context.keys()) if intersection: logger.warning( "The following default template context keys have been overridden " "by the local context: {}." .format(intersection) ) # Substitute in any other named statements recursively while '{{{' in statement or '{{%' in statement: statement = Template(statement, block_start_string='{{%', block_end_string='%}}', variable_start_string='{{{', variable_end_string='}}}', comment_start_string='{{#', comment_end_string='#}}', undefined=StrictUndefined).render(getattr(self, '_templates', {})) return Template(statement, undefined=StrictUndefined).render(template_context)