我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用jinja2.DictLoader()。
def parse(self, md_file): """ Parse a md file into a post object """ # compile the templates when we parse the first post. This is needed to ensure that # plugins get a chance to modify the templates before we compile them. if not self.jinja2: self.jinja2 = jinja2.Environment(loader=jinja2.DictLoader(self.templates)) parsed_post = utils.dict_to_objdict() # parsing frontmatter and getting the md parsed_post.meta, parsed_post.md = frontmatter.parse(md_file) # parsing markdown and extractring info # NOTE: this must called before every parsing self.renderer.init(self.jinja2, self.code_formatter, self.config.plugin_data, self.site, parsed_post.meta) parsed_post.html = self.md_parser.parse(parsed_post.md) parsed_post.meta.statistics = self.renderer.get_stats() parsed_post.meta.toc = self.renderer.get_json_toc() parsed_post.elements = self.renderer.get_info() return parsed_post
def test_scoped_block_after_inheritance(self): env = Environment(loader=DictLoader({ 'layout.html': ''' {% block useless %}{% endblock %} ''', 'index.html': ''' {%- extends 'layout.html' %} {% from 'helpers.html' import foo with context %} {% block useless %} {% for x in [1, 2, 3] %} {% block testing scoped %} {{ foo(x) }} {% endblock %} {% endfor %} {% endblock %} ''', 'helpers.html': ''' {% macro foo(x) %}{{ the_foo + x }}{% endmacro %} ''' })) rv = env.get_template('index.html').render(the_foo=42).split() assert rv == ['43', '44', '45']
def test_import(self): utils = """ {% macro print_where(value) -%} WHERE dummy_col = {{value}} {%- endmacro %} """ source = """ {% import 'utils.sql' as utils %} select * from dual {{ utils.print_where(100) }} """ loader = DictLoader({"utils.sql" : utils}) env = Environment(loader=loader) j = JinjaSql(env) query, bind_params = j.prepare_query(source, _DATA) expected_query = "select * from dual WHERE dummy_col = %s" self.assertEquals(query.strip(), expected_query.strip()) self.assertEquals(len(bind_params), 1) self.assertEquals(list(bind_params)[0], 100)
def test_get_env(test_client): app = Sanic("test_jinja2_render") # setup template = "<html><body><h1>{{Player}}</h1>{{Category}}</body></html>" jinja2_sanic.setup( app, loader=jinja2.DictLoader( { "templates.jinja2": template } ) ) env = jinja2_sanic.get_env(app) assert isinstance(env, jinja2.Environment) # consistent assert env is jinja2_sanic.get_env(app)
def test_custom_template_loader(self): class MyFlask(flask.Flask): def create_global_jinja_loader(self): from jinja2 import DictLoader return DictLoader({'index.html': 'Hello Custom World!'}) app = MyFlask(__name__) @app.route('/') def index(): return flask.render_template('index.html') c = app.test_client() rv = c.get('/') self.assert_equal(rv.data, b'Hello Custom World!')
def _gethumans(dbName, templateName): '''Return string for humans.txt.''' db = _dbAndClient(dbName)[0] metaDocs = _getMeta(db) # Get templateName from db.templates. humans = db['templates'].find_one({'name': templateName}) if not humans: raise ValueError( '%s not found in templates collection.'%(templateName)) ldr = jinja2.DictLoader({'humans': humans['data']}) env = jinja2.Environment(loader=ldr) tmplt = env.get_template('humans') # Mogrify template variables into values in the rendered page. try: humanStr = tmplt.render(metaDocs) except Exception as e: # The template probably tried to get something that isn't in meta. # Or something. e.args += (', '.join([ 'Num Docs found in meta: %d'%(len(metaDocs)), 'Names found in meta: %s'%(metaDocs.keys()), 'Template Doc: %s'%(templateName), ]),) raise return humanStr
def test_context_include_with_overrides(self): env = Environment(loader=DictLoader(dict( main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}", item="{{ item }}" ))) assert env.get_template("main").render() == "123"
def test_super(self): env = Environment(loader=DictLoader({ 'a': '{% block intro %}INTRO{% endblock %}|' 'BEFORE|{% block data %}INNER{% endblock %}|AFTER', 'b': '{% extends "a" %}{% block data %}({{ ' 'super() }}){% endblock %}', 'c': '{% extends "b" %}{% block intro %}--{{ ' 'super() }}--{% endblock %}\n{% block data ' '%}[{{ super() }}]{% endblock %}' })) tmpl = env.get_template('c') assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER'
def test_preserve_blocks(self): env = Environment(loader=DictLoader({ 'a': '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}', 'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}' })) tmpl = env.get_template('b') assert tmpl.render() == 'BA'
def test_dynamic_inheritance(self): env = Environment(loader=DictLoader({ 'master1': 'MASTER1{% block x %}{% endblock %}', 'master2': 'MASTER2{% block x %}{% endblock %}', 'child': '{% extends master %}{% block x %}CHILD{% endblock %}' })) tmpl = env.get_template('child') for m in range(1, 3): assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m
def test_scoped_block(self): env = Environment(loader=DictLoader({ 'master.html': '{% for item in seq %}[{% block item scoped %}' '{% endblock %}]{% endfor %}' })) t = env.from_string('{% extends "master.html" %}{% block item %}' '{{ item }}{% endblock %}') assert t.render(seq=list(range(5))) == '[0][1][2][3][4]'
def test_super_in_scoped_block(self): env = Environment(loader=DictLoader({ 'master.html': '{% for item in seq %}[{% block item scoped %}' '{{ item }}{% endblock %}]{% endfor %}' })) t = env.from_string('{% extends "master.html" %}{% block item %}' '{{ super() }}|{{ item * 2 }}{% endblock %}') assert t.render(seq=list(range(5))) == '[0|0][1|2][2|4][3|6][4|8]'
def test_fixed_macro_scoping_bug(self): assert Environment(loader=DictLoader({ 'test.html': '''\ {% extends 'details.html' %} {% macro my_macro() %} my_macro {% endmacro %} {% block inner_box %} {{ my_macro() }} {% endblock %} ''', 'details.html': '''\ {% extends 'standard.html' %} {% macro my_macro() %} my_macro {% endmacro %} {% block content %} {% block outer_box %} outer_box {% block inner_box %} inner_box {% endblock %} {% endblock %} {% endblock %} ''', 'standard.html': ''' {% block content %} {% endblock %} ''' })).get_template("test.html").render().split() == [u'outer_box', u'my_macro']
def set_memory_loader(app): aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'template.jinja2': '{{text}}', 'error.jinja2': '{{1/0}}', }))
def __init__(self, templates_dict=TEST_TEMPLATES, base_path="/"): self.env = Environment( loader=DictLoader(templates_dict), extensions=[ 'statik.jinja2ext.StatikUrlExtension', 'statik.jinja2ext.StatikAssetExtension' ] ) self.env.filters['date'] = filter_datetime self.env.statik_base_url = base_path self.env.statik_base_asset_url = add_url_path_component( base_path, 'assets', )
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"