{% extends "layout" %} {% extends "layout" %} {% block block1 %} {% if false %} {% block block2 %} this should workd {% endblock %} {% endif %} {% endblock %} ''' env = Environment(loader=DictLoader({ 'layout': LAYOUTTEMPLATE, 'level1': LEVEL1TEMPLATE, 'level2': LEVEL2TEMPLATE, 'level3': LEVEL3TEMPLATE, 'level4': LEVEL4TEMPLATE, 'working': WORKINGTEMPLATE, 'doublee': DOUBLEEXTENDS, }), trim_blocks=True) class InheritanceTestCase(JinjaTestCase): def test_layout(self): tmpl = env.get_template('layout') assert tmpl.render() == ('|block 1 from layout|block 2 from ' 'layout|nested block 4 from layout|') def test_level1(self): tmpl = env.get_template('level1')
#Embedded file name: jinja2/testsuite\imports.py """ jinja2.testsuite.imports ~~~~~~~~~~~~~~~~~~~~~~~~ Tests the import features (with includes). :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import unittest from jinja2.testsuite import JinjaTestCase from jinja2 import Environment, DictLoader from jinja2.exceptions import TemplateNotFound, TemplatesNotFound test_env = Environment(loader=DictLoader( dict(module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}', header='[{{ foo }}|{{ 23 }}]', o_printer='({{ o }})'))) test_env.globals['bar'] = 23 class ImportsTestCase(JinjaTestCase): def test_context_imports(self): t = test_env.from_string('{% import "module" as m %}{{ m.test() }}') t = test_env.from_string( '{% import "module" as m without context %}{{ m.test() }}') t = test_env.from_string( '{% import "module" as m with context %}{{ m.test() }}') t = test_env.from_string('{% from "module" import test %}{{ test() }}') t = test_env.from_string( '{% from "module" import test without context %}{{ test() }}') t = test_env.from_string(
def template(path, extend_path, out): """ Return a jinja2 template instance with extends support. """ files = [] # add the "extender" template when it exists if len(extend_path) > 0: # determine the base readme path base_path = os.path.dirname(extend_path) new_base_path = os.path.join(base_path, "README.{0}.j2".format(out)) if os.path.exists(new_base_path): path = new_base_path if os.path.exists(extend_path): files = [path, extend_path] else: ui.error(c.MESSAGES["template_extender_missing"]) ui.error(extend_path) sys.exit(1) else: files = [path] try: # Use the subclassed relative environment class env = RelEnvironment(trim_blocks=True) # Add a unique dict filter, by key. # DEPRECATION WARNING: This is only used for backwards compatibility, # please use the unique filter instead. def unique_dict(items, key): return {v[key]: v for v in items}.values() env.filters["unique_dict"] = unique_dict def unique(a): # Don’t use the following commented out optimization which is used # in ansible/lib/ansible/plugins/filter/mathstuff.py in Ansigenome # as it resorts the role dependencies: # if isinstance(a,collections.Hashable): # c = set(a) c = [] for x in a: if x not in c: c.append(x) return c env.filters["unique"] = unique # create a dictionary of templates templates = dict( (name, codecs.open(name, "rb", 'UTF-8').read()) for name in files) env.loader = DictLoader(templates) # return the final result (the last template in the list) return env.get_template(files[len(files) - 1]) except Exception as err: ui.error(c.MESSAGES["template_error"], err) sys.exit(1)
DesignOutput.SYSVERILOG: { 'fname': 'bag_prim.sv', 'mos': '', 'diode': '', 'diode_static': '', 'res_metal': '', }, } jinja_env = Environment( loader=DictLoader({ 'mos_cdl': mos_cdl_fmt, 'mos_scs': mos_spectre_fmt, 'mos_verilog': mos_verilog_fmt, 'diode_cdl': dio_cdl_fmt, 'diode_scs': dio_spectre_fmt, 'diode_cdl_static': dio_cdl_fmt_static, 'diode_scs_static': dio_spectre_fmt_static, 'res_metal_cdl': res_metal_cdl_fmt, 'res_metal_scs': res_metal_spectre_fmt }), keep_trailing_newline=True, ) def populate_header(config: Dict[str, Any], inc_lines: Dict[DesignOutput, List[str]], inc_list: Dict[int, List[str]]) -> None: for v, lines in inc_lines.items(): inc_list[v.value] = config[v.name]['includes']
@contextfunction def gettext(context, string): language = context.get("LANGUAGE", "en") return languages.get(language, {}).get(string, string) @contextfunction def ngettext(context, s, p, n): language = context.get("LANGUAGE", "en") if n != 1: return languages.get(language, {}).get(p, p) return languages.get(language, {}).get(s, s) i18n_env = Environment( loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"] ) i18n_env.globals.update({"_": gettext, "gettext": gettext, "ngettext": ngettext}) i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"]) i18n_env_trimmed.policies["ext.i18n.trimmed"] = True i18n_env_trimmed.globals.update( {"_": gettext, "gettext": gettext, "ngettext": ngettext} ) newstyle_i18n_env = Environment( loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"] ) newstyle_i18n_env.install_gettext_callables( # type: ignore gettext, ngettext, newstyle=True )
def test_correct_prefix_loader_name(self, env): env = Environment(loader=PrefixLoader({"foo": DictLoader({})})) with pytest.raises(TemplateNotFound) as e: env.get_template("foo/bar.html") assert e.value.name == "foo/bar.html"
@contextfunction def gettext(context, string): language = context.get('LANGUAGE', 'en') return languages.get(language, {}).get(string, string) @contextfunction def ngettext(context, s, p, n): language = context.get('LANGUAGE', 'en') if n != 1: return languages.get(language, {}).get(p, p) return languages.get(language, {}).get(s, s) i18n_env = Environment(loader=DictLoader(i18n_templates), extensions=['jinja2.ext.i18n']) i18n_env.globals.update({ '_': gettext, 'gettext': gettext, 'ngettext': ngettext }) newstyle_i18n_env = Environment(loader=DictLoader(newstyle_i18n_templates), extensions=['jinja2.ext.i18n']) newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True) class ExampleExtension(Extension): tags = set(['test']) ext_attr = 42
def _render_once(self, template_string): loader = DictLoader({'template': template_string}) env = Environment(loader=loader) template = env.get_template('template') return template.render(**self.context)
def compile_template(template_dict, template_name): """Compile template.""" env = Environment(loader=DictLoader(template_dict)) template = env.get_template(template_name) return template
def _env(self): return (EnvBuilder().set_loader(DictLoader( self.templates)).set_globals_module( globals_module).set_filters_package(filters_package).build())
from sanic.log import logger app.static('/static', 'app/static') css_files = ['main', 'base', 'navbar', 'forms', 'database', 'pokertables', 'pokertable'] getHeaders = { 'css_urls': [app.url_for('static', filename=f'css/{file}.css') for file in css_files], 'favicon_url': app.url_for('static', filename='favicon.ico') } setup(app, loader=DictLoader({ "template_base": open('app/templates/base.html').read(), "template_signin": open('app/templates/signin.html').read(), "template_signup": open('app/templates/signup.html').read(), "template_database": open('app/templates/database.html').read(), "template_table": open('app/templates/table.html').read(), "template_pokertables": open('app/templates/pokertables.html').read() })) def signinValidate(form): password = form.get('password').encode('utf-8') passhash = sha256(password).hexdigest() account = dbase.selectWhere( DbTable.ACCOUNTS, username = form.get('username'), password_hash = passhash ) return bool(account) def signupValidate(form):
app.jinja_env.loader = DictLoader({ 'document.html': ''' <!doctype html> <title>Test document</title> <link rel=stylesheet href="{{ url_for('static', filename='style.css') }}" /> <body> <section> <h1><a href="http://packages.python.org/Flask-WeasyPrint/"> Flask-WeasyPrint</a> demo</h1> <nav>Get this document <a href="/foo.pdf">as PDF</a> or <a href="/foo.png">as PNG</a>.</nav> <p>This vector graph was generated dynamically:</p> <img src=graph?data={{ data|join(',') }}&labels={{ labels|join(',') }}> </section> ''', 'graph.svg': ''' <svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1000" viewBox="0 0 160 100"> <style> text { text-anchor: middle; font-size: 10px } </style> {% for i, (label, value, color) in series %} <rect x="{{ 10 + i * 50 }}" y="{{ 75 - value }}" width="40" height="{{ value }}" fill="{{ color }}" stroke="#333" rx="5" ry="5" /> <text x="{{ 30 + i * 50 }}" y="90">{{ label }}</text> {% endfor %} </svg> ''', })
def test_include(self, env_trim): env_trim = Environment(loader=DictLoader( {"include": "{% macro test(foo) %}[{{ foo }}]{% endmacro %}"})) tmpl = env_trim.from_string( '{% from "include" import test %}{{ test("foo") }}') assert tmpl.render() == "[foo]"
def convert_to_body_resources(notebook_filename, bibtex_filename): ## Initializing resources to have correct output directory notebook_name = notebook_filename.split('/')[-1].replace('.ipynb', '') #see https://github.com/jupyter/nbconvert/blob/fcc3a831295b373a7a9ee5e8e0dea175475f8f26/nbconvert/nbconvertapp.py#L288 resources = {} #resources['config_dir'] = self.config_dir resources['unique_key'] = notebook_name resources['output_files_dir'] = '%s_files' % notebook_name own_notebook = nbformat.read(notebook_filename, as_version=4) # replace cite keys by bibtex citekeys: if bibtex_filename is not None and 'cite2c' in own_notebook['metadata']: with open(bibtex_filename, 'r') as bibtex_file: bibtex = bibtexparser.load(bibtex_file) cite2_key_to_bibtex_key = dict() for key, cite2c_entry in own_notebook['metadata']['cite2c']['citations'].iteritems(): equal_bibtex_entries = [b for b in bibtex.entries if cite2c_bibtex_equal(cite2c_entry,b)] if (len(equal_bibtex_entries) == 1): cite2_key_to_bibtex_key[key] = equal_bibtex_entries[0]['ID'] assert len(equal_bibtex_entries) < 2, ("expected at most " "one equal bibtex entry, got {:s}".format(str(equal_bibtex_entries))) for cell in own_notebook['cells']: for cite2_key, bibtex_key in cite2_key_to_bibtex_key.iteritems(): if cell['cell_type'] == 'markdown': cell['source'] = cell['source'].replace(cite2_key, bibtex_key) # find imgs and convert to resources resources['outputs'] = dict() for cell in own_notebook['cells']: if cell['cell_type'] == 'markdown': img_urls_filenames = re.findall(r"<img.*src=\"([^>]*/([^\.]*\.[a-z]*)[^\"]*)\"[^>]*>[^<]*</img>", cell['source']) for url, img_filename in img_urls_filenames: response = requests.get(url, stream=True) all_blocks = [] if not response.ok: continue for block in response.iter_content(1024): all_blocks.append(block) data = ''.join(all_blocks) if img_filename.endswith('svg'): svg_2_pdf = SVG2PDFPreprocessor() pdfdata = svg_2_pdf.convert_figure(None, data) pdfdata = base64.decodestring(pdfdata) # it is encoded by svg2pdfpreproc.. not sure if decoding is necessary img_filename = img_filename.replace('.svg', '.pdf') data = pdfdata if img_filename.endswith('gif'): jpgdata = gif_to_jpg(data) img_filename = img_filename.replace('.gif', '.jpg') data = jpgdata resource_key = os.path.join(resources['output_files_dir'], img_filename) resources['outputs'][resource_key] = data # Replace the whole image tag by latex code with the correct filename cell['source'] = re.sub(r"<img.*src=\"[^>]*/([^\.]*\.[a-z]*)[^>]*>[^<]*</img>", "\\\\begin{center}\n" + "\\\\adjustimage{max size={0.9\\linewidth}{0.9\\paperheight}}{" + resources['output_files_dir'] + "/" + r"\1" + # here is the filename "}\n"+ "\\end{center}\n", cell['source']) cell['source'] = cell['source'].replace('.svg', '.pdf') cell['source'] = cell['source'].replace('.gif', '.jpg') # remove javascript/html outputs for cell in own_notebook['cells']: if cell['cell_type'] == 'code' and 'outputs' in cell: cell['outputs'] = remove_javascript_html_outputs(cell['outputs']) # do some custom replacements of html for cell in own_notebook['cells']: if cell['cell_type'] == 'markdown': cell['source'] = cell['source'].replace('<span class="todecide">', '\\begin{comment}\nTODECIDE\n') cell['source'] = cell['source'].replace('<span class="todo">', '\\begin{comment}\nTODO\n') cell['source'] = cell['source'].replace('</span>', '\n\\end{comment}\n') cell['source'] = cell['source'].replace("<div class=\"summary\">", "\\begin{keypointbox}") cell['source'] = cell['source'].replace("</div>", "\\end{keypointbox}") cell['source'] = cell['source'].replace("<li>", "\\item ") cell['source'] = cell['source'].replace("</li>", "").replace("<ul>", "").replace("</ul>", "") dl = DictLoader({'article.tplx': """ ((*- extends 'base.tplx' -*)) ((* block header *)) ((* endblock header *)) % only part-document, not complete document, so call not base constructor, but the one above ((* block body *)) ((( super.super() ))) ((* endblock body *)) % is this removing code? unclear.. probaby removing stdout/stdin ((* block stream *)) ((* endblock stream *)) % Remove execute result stuff ((* block execute_result scoped *)) ((* endblock execute_result *)) ((* macro draw_figure(filename) -*)) ((* set filename = filename | posix_path *)) ((*- block figure scoped -*)) %\\begin{figure}[ht] \\begin{center} \\adjustimage{max size={0.9\\linewidth}{0.9\\paperheight}}{((( filename )))} \\end{center} %\\end{figure} %{ \\hspace*{\\fill} \\\\} ((*- endblock figure -*)) ((*- endmacro *)) ((* block markdowncell scoped *)) ((( cell.source | citation2latex | strip_files_prefix | markdown2latex(extra_args=["--chapters"]) ))) ((* endblock markdowncell *)) """}) exportLatex = LatexExporter(extra_loaders=[dl]) (body, resources) = exportLatex.from_notebook_node(own_notebook,resources=resources) # postprocess url links with footnotes body = re.sub(r"(\\href{([^}]*)}{[^}]*})", r"\1\\footnote{\\url{\2}}", body) return body, resources
#Embedded file name: c:\depot\games\branches\release\EVE-TRANQUILITY\carbon\common\lib\jinja2\testsuite\inheritance.py import unittest from jinja2.testsuite import JinjaTestCase from jinja2 import Environment, DictLoader LAYOUTTEMPLATE = '|{% block block1 %}block 1 from layout{% endblock %}\n|{% block block2 %}block 2 from layout{% endblock %}\n|{% block block3 %}\n{% block block4 %}nested block 4 from layout{% endblock %}\n{% endblock %}|' LEVEL1TEMPLATE = '{% extends "layout" %}\n{% block block1 %}block 1 from level1{% endblock %}' LEVEL2TEMPLATE = '{% extends "level1" %}\n{% block block2 %}{% block block5 %}nested block 5 from level2{%\nendblock %}{% endblock %}' LEVEL3TEMPLATE = '{% extends "level2" %}\n{% block block5 %}block 5 from level3{% endblock %}\n{% block block4 %}block 4 from level3{% endblock %}\n' LEVEL4TEMPLATE = '{% extends "level3" %}\n{% block block3 %}block 3 from level4{% endblock %}\n' WORKINGTEMPLATE = '{% extends "layout" %}\n{% block block1 %}\n {% if false %}\n {% block block2 %}\n this should workd\n {% endblock %}\n {% endif %}\n{% endblock %}\n' env = Environment(loader=DictLoader({ 'layout': LAYOUTTEMPLATE, 'level1': LEVEL1TEMPLATE, 'level2': LEVEL2TEMPLATE, 'level3': LEVEL3TEMPLATE, 'level4': LEVEL4TEMPLATE, 'working': WORKINGTEMPLATE }), trim_blocks=True) class InheritanceTestCase(JinjaTestCase): def test_layout(self): tmpl = env.get_template('layout') def test_level1(self): tmpl = env.get_template('level1') def test_level2(self): tmpl = env.get_template('level2')
mapping = (("%7B%7B", "{{"), ("%7D%7D", "}}"), ("%20", " ")) for k, v in mapping: transformed_template = transformed_template.replace(k, v) transformed[filename] = transformed_template return transformed def _load_templates(): templates = dict() for filename in os.listdir(TEMPLATES_DIR): if filename.endswith(".html") or filename.endswith(".xml"): with open(os.path.join(TEMPLATES_DIR, filename), "r") as html: templates[filename] = html.read() return templates def render_email(template_name, **kwargs): """ Email templates are compiled outside the normal flask environment, using premailer. As a result, they don't have access to the flask context. For consistency, we add the `config` variable to the context. However other flask functions, like `url_for` can't be used in an email template. """ template = _ENVIRONMENT.get_template(template_name) kwargs["config"] = settings return template.render(**kwargs) _SOURCE_MAP = _do_premailer(_do_includes(_load_templates())) _ENVIRONMENT = Environment(loader=DictLoader(_SOURCE_MAP))
def build_convert_engine(self, *, context): self.headers = None environment = Environment(loader=DictLoader(context.template)) self.template = environment.get_template(context.template_name)
def test_set_and_include(self): env = Environment(loader=DictLoader({ 'inc': 'bar', 'main': '{% set foo = "foo" %}{{ foo }}{% include "inc" %}' })) assert env.get_template('main').render() == 'foobar'
def test_block_set_with_extends(self): env = Environment(loader=DictLoader( {"main": "{% block body %}[{{ x }}]{% endblock %}"})) t = env.from_string('{% extends "main" %}{% set x %}42{% endset %}') assert t.render() == "[42]"
def test_loop_include(self): env = Environment(loader=DictLoader({ 'inc': '{{ item }}', 'main': '{% for item in [1, 2, 3] %}{% include "inc" %}{% endfor %}', })) assert env.get_template('main').render() == '123'
# -*- coding: utf-8 -*- from jinja2 import Environment, DictLoader from clay.tglobals import IncludeWith env = Environment(loader=DictLoader({ 'hello': 'Hello {{ what }}!', 'sum': '{{ a }} + {{ b }} makes {{ c }}', }), extensions=['jinja2.ext.with_', IncludeWith]) def test_set_context(): tmpl = env.from_string( '''{% include "hello" with what='world' %} {% include "hello" with what='world' %}''' ) expected = '''Hello world! Hello world!''' result = tmpl.render() assert result == expected def test_overwrite_context(): tmpl = env.from_string(''' {% include "hello" with what='world' %} {% include "hello" with what='world' %} ''') expected = ''' Hello world! Hello world! ''' result = tmpl.render(what='you')
def test_include(): env = Environment(loader=DictLoader({'include': INCLUDETEMPLATE})) tmpl = env.from_string('{% from "include" import test %}{{ test("foo") }}') assert tmpl.render() == '[foo]'
def test_correct_prefix_loader_name(self): env = Environment(loader=PrefixLoader({'foo': DictLoader({})})) try: env.get_template('foo/bar.html') except TemplateNotFound, e: assert e.name == 'foo/bar.html'
{% endif %} been released! Get {% if plural %} them {% else %} it {% endif %} on PyPI: pip install ansible{% if is_ansible_base(version) %}-base{% endif %}=={{ version }}, the Ansible PPA on Launchpad, or GitHub. Happy automating! """ # noqa for E501 (line length). # jinja2 is horrid about getting rid of extra newlines so we have to have a single per paragraph for # proper wrapping to occur JINJA_ENV = Environment( loader=DictLoader({'long': LONG_TEMPLATE, 'short': SHORT_TEMPLATE, 'version_string': VERSION_FRAGMENT, }), extensions=['jinja2.ext.i18n'], trim_blocks=True, lstrip_blocks=True, ) async def calculate_hash_from_tarball(session, version): tar_url = f'https://pypi.python.org/packages/source/a/ansible-base/ansible-base-{version}.tar.gz' tar_task = asyncio.create_task(session.get(tar_url)) tar_response = await tar_task tar_hash = hashlib.sha256() while True: chunk = await tar_response.content.read(1024)
def create_global_jinja_loader(self): from jinja2 import DictLoader return DictLoader({'index.html': 'Hello Custom World!'})
operator {{type}}() const; {{class}}& operator=({{type}}); """ PCDATA_OPERATOR_DEFINITION = """ bmml::{{class}}::operator {{type}}() const { return boost::lexical_cast<{{type}}>(text()); } bmml::{{class}}& bmml::{{class}}::operator=({{type}} value) { text(boost::lexical_cast<std::string>(value)); return *this; } """ templates = Environment(loader=DictLoader(globals())) from lxml.etree import DTD enumerations = { ('full', 'part', 'division'): { 'name': 'inaccord_t' }, ('left_toe', 'left_heel', 'right_toe', 'right_heel'): { 'name': 'organ_pedal_t' }, ('full', 'half', 'caesura'): { 'name': 'full_half_caesura' }, ('full', 'half', 'vertical'): { 'name': 'full_half_vertical'
def test_context_include_with_overrides(self): env = Environment(loader=DictLoader( dict(main= "{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}", item='{{ item }}')))
from IPython.nbconvert import HTMLExporter from IPython.nbformat import current as nbformat from docutils.core import publish_doctree, publish_parts from docutils import nodes from glob import glob from jinja2 import DictLoader from contingent.projectlib import Project from contingent.io import looping_wait_on dl = DictLoader({ 'full.tpl': """\ {%- extends 'display_priority.tpl' -%} {% block input scoped %}<pre>{{ cell.input }}</pre> {% endblock %} {% block pyout scoped %}<pre>{{ output.text | ansi2html }}</pre> {% endblock %} {% block markdowncell scoped %}{{ cell.source | markdown2html }} {% endblock %} """ }) project = Project() task = project.task @task def read_text_file(path): with open(path) as f: return f.read()
def test_context_include_with_overrides(self, test_env_async): 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_include(self): self.env = Environment(loader=DictLoader( {'include': '{% macro test(foo) %}[{{ foo }}]{% endmacro %}'})) tmpl = self.env.from_string( '{% from "include" import test %}{{ test("foo") }}')