How to use the jinja2.Template function in Jinja2

To help you get started, we’ve selected a few Jinja2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github joerick / cibuildwheel / test / test_projects / c.py View on Github external
def new_c_project(*, spam_c_top_level_add='', spam_c_function_add='', setup_py_add='',
                  setup_py_setup_args_add='', setup_cfg_add=''):
    project = TestProject()

    project.files.update({
        'spam.c': jinja2.Template(SPAM_C_TEMPLATE),
        'setup.py': jinja2.Template(SETUP_PY_TEMPLATE),
        'setup.cfg': jinja2.Template(SETUP_CFG_TEMPLATE),
    })

    project.template_context.update({
        'spam_c_top_level_add': spam_c_top_level_add,
        'spam_c_function_add': spam_c_function_add,
        'setup_py_add': setup_py_add,
        'setup_py_setup_args_add': setup_py_setup_args_add,
        'setup_cfg_add': setup_cfg_add,
    })

    return project
github sci-bots / microdrop / generate_wxs.py View on Github external
extra_dirs = ['etc', 'gui', 'mpl-data', 'share', 'pygtkhelpers',
            'opencv_helpers', 'flatland', 'support', 'gst', 'pygst_utils',
            'glade', 'pygst_utils_windows_server']
    children = dict([(name, dw.xml_tree(root_path.joinpath(name),
            recursive=True)) for name in extra_dirs])

    devices = dw.xml_tree(root_path.joinpath('devices'), recursive=True)
    plugins = dw.xml_tree(root_path.joinpath('plugins'), recursive=True)

    for c in children.itervalues():
        root[0].appendChild(c[0])

    all_components = list(itertools.chain(*[c[1] for c in children.itervalues()]))
    all_components += root[1] + devices[1] + plugins[1]

    t = jinja2.Template(WXS_TEMPLATE)

    return t.render(id='Microdrop', title='Microdrop',
                    dir_tree=root[0].toprettyxml(indent='  '),
                    device_tree=devices[0].toprettyxml(indent='  '),
                    plugins_tree=plugins[0].toprettyxml(indent='  '),
                    components=all_components,
                    root=root[0].getAttribute('Id'), version=version)
github apache / incubator-ariatosca / aria / parser / reading / jinja.py View on Github external
def read(self):
        data = self.load()
        try:
            data = unicode(data)
            template = Template(data)
            literal = template.render(CONTEXT)
            # TODO: might be useful to write the literal result to a file for debugging
            location = self.location
            if isinstance(location, basestring) and location.endswith('.jinja'):
                # Use reader based on the location with the ".jinja" prefix stripped off
                location = location[:-6]
                next_reader = self.context.reading.reader_source.get_reader(
                    self.context, LiteralLocation(literal, name=location), LiteralLoader(literal))
            else:
                # Use reader for literal loader
                next_reader = self.context.reading.reader_source.get_reader(
                    self.context, LiteralLocation(literal), LiteralLoader(literal))
            return next_reader.read()
        except Exception as e:
            raise ReaderSyntaxError(u'Jinja: {0}'.format(e), cause=e)
github nre-learning / nrelabs-curriculum / lessons / workflows / lesson-35-devicespecifictemplate / stage2 / build-configs.py View on Github external
#!/usr/bin/python

import yaml
from jinja2 import Template

var_file = open('variables.yml')
var_data = var_file.read()
my_vars = yaml.full_load(var_data)

template_file = open('template.j2')
template_data = template_file.read()
template = Template(template_data)

for device in my_vars:
	print "Creating config for " + device["HOSTNAME"]
	outfile = open(device["HOSTNAME"] + ".conf", "w")
	outfile.write(template.render(device))
	outfile.close()
github Mirantis / solar / solar / solar / core / data.py View on Github external
iter_ctx[iter_key] = item
                    result_list.append(self.render(value[iter_key], iter_ctx, previous_render))

                return result_list

            else:
                # Handle usual data
                result_dict = {}
                for k, v in value.items():
                    result_dict[k] = self.render(v, context, previous_render)

                return result_dict
        elif isinstance(value, list):
            return map(lambda v: self.render(v, context, previous_render), value)
        elif isinstance(value, str):
            env = Template(value)
            return env.render(**context)
        else:
            # If non of above return value, e.g. if there is
            # interger, float etc
            return value
github ofosos / scratch / monitoring / gen-shinken.py View on Github external
check_command check_dummy!0!Very well
  check_interval 5
  retry_interval 1
  max_check_attempts 5
  check_period 24x7
  process_perf_data 0
  retain_nonstatus_information 0
  contact_groups admins
  notification_interval 3600
  notification_period none
  notification_options 
}

""")

service_template = Template("""define service {
  host_name {{ host }}
  service_description {{ service }}
  check_command check_dummy!0!Very well
  max_check_attempts 5
  check_interval 5
  retry_interval 1
  check_period 24x7
  notification_interval 3600
  notification_period none
  contact_groups admins
}

""")

hostgroup_template = Template("""define hostgroup {
  hostgroup_name {{ hostgroup }}
github iseekwonderful / PyPathway / pypathway / exportion / __init__.py View on Github external
def generate_page_for_each_result(config):
        data = {}
        for i, x in enumerate(config['detail']):
            data[config['snapshot'][i]['id']] = x
        template_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', 'enrichment')
        with open(template_path + '/js/enrichment_display_template') as fp:
            con = fp.read()
        t = Template(con)
        with open(template_path + '/js/enrichment_display3.js', 'w') as fp:
            fp.write(t.render(type='local', data=json.dumps(data)))
        with open(template_path + '/data/data2.json', 'w') as fp:
            json.dump(data, fp)
        with open(template_path + '/enrichment_display.html') as fp:
            con = fp.read()
        for i, x in enumerate(config['snapshot']):
            t = Template(deepcopy(con))
            with open(template_path + "/details/{}.html".format(x['id']), 'w') as fp:
                fp.write(t.render(table=config['detail'][i]['table']))
github mickep76 / pepa / src / pepa.py View on Github external
if category not in input:
            continue

        entries = []
        if type(input[category]) is list:
            entries = input[category]
        else:
            entries = [ input[category] ]

        for entry in entries:
            results = None
            fn = makepath(basedir,  input['environment'], resource, 'templates', category,
                re.sub('\W', '_', entry.lower()))
            if isfile(fn + '.yaml'):
                info("Load template: %s.yaml" % fn)
                template = jinja2.Template(open(fn + '.yaml').read())
                results = yaml.load(template.render(output))
            elif isfile(fn + '.json'):
                info("Load template: %s.json" % fn)
                template = jinja2.Template(open(fn + '.yaml').read())
                results = json.loads(template.render(output))
            else:
                warn("Template doesn't exist: %s.(json|yaml)" % fn)
                continue

            if results != None:
                for key in results:
                    info("Substituting key: %s" % key, 'yellow')
                    output[key] = results[key]
    return output
github mozilla-services / socorro / bixie / bin / crontab / gen-crons.py View on Github external
if not opts.webapp:
        parser.error('-w must be defined')

    ctx = {'django': 'cd %s; %s manage.py' % (opts.webapp, opts.python)}
    ctx['cron'] = '%s cron' % ctx['django']

    if opts.user:
        for k, v in ctx.iteritems():
            ctx[k] = '%s %s' % (opts.user, v)

    # Needs to stay below the opts.user injection.
    ctx['python'] = opts.python
    ctx['header'] = HEADER

    print Template(TEMPLATE).render(**ctx)
github zstackio / zstack-utility / zstacklib / zstacklib / utils / bash.py View on Github external
def bash_roe(cmd, errorout=False, ret_code = 0):
    frames = []
    frame = inspect.currentframe()
    while frame:
        frames.insert(0, frame)
        frame = frame.f_back

    ctx = {}
    for f in frames:
        ctx.update(f.f_locals)

    tmpt = Template(cmd)
    cmd = tmpt.render(ctx)

    p = subprocess.Popen('/bin/bash', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
    o, e = p.communicate(cmd)
    r = p.returncode

    __BASH_DEBUG_INFO__ = ctx.get('__BASH_DEBUG_INFO__')
    if __BASH_DEBUG_INFO__ is not None:
        __BASH_DEBUG_INFO__.append({
            'cmd': cmd,
            'return_code': p.returncode,
            'stdout': o,
            'stderr': e
        })

    if r != ret_code and errorout: