How to use the jinja2.Environment 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 UCCNetsoc / netsocadmin2 / wordpress_installer / wordpress_installer / calibrate.py View on Github external
def calibrate():
	print("Configuring Wordpress installer")

	log_location = os.path.dirname(__file__) + '/resources/wordpress_installer.log'
	try:
		os.remove(log_location)
	except Exception as e:
		pass

	env = Environment(loader=PackageLoader('wordpress_installer', '/resources/templates'))
	log_config_template = env.get_template('logging_config.ini.j2') 
	log_config = log_config_template.render(LOG_LOCATION=log_location)
	
	log_config_location = os.path.dirname(__file__) + "/resources/logging_config.ini"

	with open(log_config_location, "w") as fh:
		fh.write(log_config)

	print("Writing Files Complete!")
github mikelambert / dancedeets-monorepo / server / dancedeets / base_servlet.py View on Github external
def __init__(self, *args, **kwargs):
        self.display = {}
        self._errors = []

        self.jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(['templates', 'dist/templates']), autoescape=True)

        # This is necessary because appengine comes with Jinja 2.6 pre-installed, and this was added in 2.7+.
        def do_urlencode(value):
            """Escape for use in URLs."""
            return urllib.quote(value.encode('utf8'))

        self.jinja_env.filters['urlencode'] = do_urlencode
        self.jinja_env.filters['format_html'] = text.format_html
        self.jinja_env.filters['escapejs'] = text.escapejs
        self.jinja_env.filters['tojson'] = text.tojson_filter
        self.jinja_env.globals['zip'] = zip
        self.jinja_env.globals['len'] = len

        # We can safely do this since there are very few ways others can modify self._errors
        self.display['errors'] = self._errors
        # functions, add these to some base display setup
github OfWolfAndMan / CCIE-Lab-Automation / Automatelab.py View on Github external
def render_templates():
	from jinja2 import Environment, FileSystemLoader, Template
	ENV = Environment(loader=FileSystemLoader('./'))

	with open("device-vars.yml") as main_variables:
		main_variables = yaml.load(main_variables)
	with open("device-vars.yml") as main_variables_two:
	    Devices = (yaml.load(main_variables_two))['Devices']
	template = ENV.get_template("Baseline&Hardening_Configurations/Templates/Base&Hardening.template")
	for DeviceName in Devices:
		if "IOSV" in DeviceName or "R" in DeviceName:
			with open("Baseline&Hardening_Configurations/Builds/{}.cfg".format(DeviceName), 'w') as config_output:
				config_template = template.render(main_variables, hostname=DeviceName, mgmt_ip=Devices[DeviceName]['mgmt_ip'], mgmt_mask=Devices[DeviceName]['mgmt_mask'])
				config_output.write(config_template)
			config_output.close()
def get_the_facts():
github googleapis / gapic-generator-python / gapic / generator / generator.py View on Github external
def __init__(self, opts: options.Options) -> None:
      # Create the jinja environment with which to render templates.
        self._env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(searchpath=opts.templates),
            undefined=jinja2.StrictUndefined,
            extensions=["jinja2.ext.do"],
        )

        # Add filters which templates require.
        self._env.filters["rst"] = utils.rst
        self._env.filters["snake_case"] = utils.to_snake_case
        self._env.filters["sort_lines"] = utils.sort_lines
        self._env.filters["wrap"] = utils.wrap
        self._env.filters["coerce_response_name"] = coerce_response_name

        self._sample_configs = opts.sample_configs
github krpc / krpc / tools / krpctools / krpctools / docgen / __init__.py View on Github external
def process_file(domain, services, path):
    loader = jinja2.FileSystemLoader(searchpath=[
        domain.macros_dir,
        os.path.abspath(os.path.dirname(path))])
    template_env = jinja2.Environment(
        loader=loader,
        trim_blocks=True,
        lstrip_blocks=True,
        undefined=jinja2.StrictUndefined,
        extensions=[AppendExtension]
    )

    def hasdoc(xml, selector='./summary'):
        return DocumentationGenerator(domain, services, xml).has(selector)

    def gendoc(xml, selector='./summary'):
        return DocumentationGenerator(domain, services, xml).generate(selector)

    def see(cref):
        obj = lookup_cref(cref, services)
        return domain.see(obj)
github moraes / tipfy / experimental / tipfyext / jinja2 / __init__.py View on Github external
elif cfg.get('use_compiled'):
            compiled_target = os.path.join(templates_dir, '_compiled')
        else:
            compiled_target = None

        use_compiled = not app.debug or cfg.get('force_use_compiled')

        if compiled_target is not None and use_compiled:
            # Use precompiled templates loaded from a module or zip.
            loader = ModuleLoader(compiled_target)
        else:
            # Parse templates for every new environment instances.
            loader = FileSystemLoader(templates_dir)

        # Initialize the environment.
        env = Environment(loader=loader, extensions=extensions)

        if _globals:
            env.globals.update(_globals)

        if filters:
            env.filters.update(filters)

        if i18n:
            # Install i18n.
            env.add_extension('jinja2.ext.i18n')
            trans = i18n.get_translations
            env.install_gettext_callables(
                lambda s: trans().ugettext(s),
                lambda s, p, n: trans().ungettext(s, p, n),
                newstyle=True)
github bogdanvuk / pygears / pygears / hls / compile_snippets.py View on Github external
def get_jinja_env():
    jenv = jinja2.Environment()
    jenv.filters['macro'] = call_macro_by_name
    return jenv
github spyder-ide / spyder / spyderlib / utils / inspector / sphinxify.py View on Github external
def usage(title, message, tutorial_message, tutorial):
    """Print a usage message on the rich text view"""
    env = Environment()
    env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates'))
    usage = env.get_template("usage.html")
    return usage.render(css_path=CSS_PATH, title=title, intro_message=message,
                        tutorial_message=tutorial_message, tutorial=tutorial)
github probstj / ccGains / ccgains / reports.py View on Github external
:param locale: None or locale identifier, e.g. 'de_DE' or 'en_US';
            The locale used for formatting numeric and date values with
            babel. If None (default), the locale will be taken from the
            `LC_NUMERIC` or `LC_TIME` environment variables on your
            system, for numeric or date values, respectively.
        :param extended_data: Boolean, default: False;
            If the *template_file* makes use of some of the extended data
            returned from `get_report_data` when called with parameter
            `extended=True`, this must also be True. See documentation
            of `get_report_data` for extended data fields.
        :returns:
            HTML-formatted string

        """

        env = jinja2.Environment(
                loader=jinja2.PackageLoader('ccgains', 'templates'))

        df = self.get_report_data(
                year=year,
                date_precision=date_precision, combine=combine,
                convert_timezone=convert_timezone,
                # Don't strip timezone, will be handled by formatters:
                strip_timezone=False,
                extended=extended_data)

        total_profit = df['profit'].sum()
        # taxable profit is zero if long_term:
        df['profit'] = df['profit'].where(df['short_term'], 0)
        short_term_profit = df['profit'].sum()

        # use custom column names:
github materialsproject / crystaltoolkit / crystal_toolkit / helpers / asymptote_renderer.py View on Github external
def asy_write_data(input_scene_comp, fstream):
    """
    parse a primitive display object in crystaltoolkit and print it to asymptote
    input_scene_comp
    fstream
    """
    if input_scene_comp["type"] == "spheres":
        positions = input_scene_comp["positions"]
        positions = [tuple(pos) for pos in positions]

        fstream.write(
            Environment()
            .from_string(TEMP_SPHERE)
            .render(
                positions=positions,
                radius=input_scene_comp["radius"],
                color=input_scene_comp["color"].replace("#", ""),
            )
        )

    if input_scene_comp["type"] == "cylinders":
        # need to transforme all the cylinders to vector
        posPairs = [
            [tuple(ipos), tuple(fpos)]
            for ipos, fpos in input_scene_comp["positionPairs"]
        ]
        fstream.write(
            Environment()