Load a Jinja2 template from the source directory.
357255
def load_template(self, template: str) -> Template:
        """"""
        env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False)
        jinja2_ext = ".jinja2"
        if not template.endswith(jinja2_ext):
            self._log.error("Template file name must end with %s" % jinja2_ext)
            raise ValueError
        if not template[:-len(jinja2_ext)].endswith(".md"):
            self._log.error("Template file should be a Markdown file.")
            raise ValueError
        if not os.path.isabs(template):
            template = os.path.join(os.path.dirname(__file__), template)
        with open(template, encoding="utf-8") as fin:
            template_obj = Template(fin.read(), **env)
        template_obj.filename = template
        self._log.info("Loaded %s", template)
        return template_obj
752389
def get_template_sources(template_name, template_dirs=None):
        
        if not connection.tenant or isinstance(connection.tenant, FakeTenant):
            return
        if not template_dirs:
            try:
                template_dirs = settings.MULTITENANT_TEMPLATE_DIRS
            except AttributeError:
                raise ImproperlyConfigured('To use %s.%s you must define the MULTITENANT_TEMPLATE_DIRS' %
                                           (__name__, FilesystemLoader.__name__))
        for template_dir in template_dirs:
            try:
                if '%s' in template_dir:
                    yield safe_join(template_dir % connection.tenant.domain_url, template_name)
                else:
                    yield safe_join(template_dir, connection.tenant.domain_url, template_name)
            except UnicodeDecodeError:
                # The template dir name was a bytestring that wasn't valid UTF-8.
                raise
            except ValueError:
                # The joined path was located outside of this particular
                # template_dir (it might be inside another one, so this isn't
                # fatal).
                pass
116127
def load_file_template(path):
    
    template = StringIO()
    if not os.path.exists(path):
        raise ValueError("path does not exist: %s" % path)
    with open(clean_path(path), "rb") as infile:  # opened as binary
        for line in infile:
            template.write(line.decode("utf-8"))  # ensure utf-8
    return template
667364
def _jinja_executor_template(self):
        """"""
        template = self.campaign.process.executor_template
        if template.startswith('#!'):
            return jinja_environment.from_string(template)
        else:
            return jinja_environment.get_template(template)
1074705
def get_template_from_config(self, config):
        
        if config["output"]["template"] == "default":
            return os.path.join(
                os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                'template',
                'default.html'
            )
        else:
            return os.path.abspath(config["output"]["template"])
1322193
def copy_template(template_name, copy_to, tag_library_name):
    """"""
    import django_extensions
    import shutil

    template_dir = os.path.join(django_extensions.__path__[0], 'conf', template_name)

    # walk the template structure and copies it
    for d, subdirs, files in os.walk(template_dir):
        relative_dir = d[len(template_dir) + 1:]
        if relative_dir and not os.path.exists(os.path.join(copy_to, relative_dir)):
            os.mkdir(os.path.join(copy_to, relative_dir))
        for i, subdir in enumerate(subdirs):
            if subdir.startswith('.'):
                del subdirs[i]
        for f in files:
            if f.endswith('.pyc') or f.startswith('.DS_Store'):
                continue
            path_old = os.path.join(d, f)
            path_new = os.path.join(copy_to, relative_dir, f.replace('sample', tag_library_name))
            if os.path.exists(path_new):
                path_new = os.path.join(copy_to, relative_dir, f)
                if os.path.exists(path_new):
                    continue
            path_new = path_new.rstrip(".tmpl")
            fp_old = open(path_old, 'r')
            fp_new = open(path_new, 'w')
            fp_new.write(fp_old.read())
            fp_old.close()
            fp_new.close()
            try:
                shutil.copymode(path_old, path_new)
                _make_writeable(path_new)
            except OSError:
                sys.stderr.write("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)
334701
def build(template_directories):
    
    template = load_template(template_directories[0])
    for directory in template_directories[1:]:
        template.update(load_template(directory))
    return template
1285218
def render(filename, obj):
    """"""
    template_path = abspath(filename)
    env = jinja_env(template_path)
    template_base = os.path.basename(template_path)
    try:
        parsed_content = env.parse(env
                                   .loader
                                   .get_source(env, template_base))
        template_vars = meta.find_undeclared_variables(parsed_content)
        if template_vars:
            missing_vars(template_vars, parsed_content, obj)

        LOG.debug("rendering %s with %s vars",
                  template_path, len(template_vars))
        return env \
            .get_template(template_base) \
            .render(**obj)
    except jinja2.exceptions.TemplateSyntaxError as exception:
        template_trace = traceback.format_tb(sys.exc_info()[2])
        # Different error context depending on whether it is the
        # pre-render variable scan or not
        if exception.filename:
            template_line = template_trace[len(template_trace) - 1]
            raise aomi_excep.Validation("Bad template %s %s" %
                                        (template_line,
                                         str(exception)))

        template_str = ''
        if isinstance(exception.source, tuple):
            # PyLint seems confused about whether or not this is a tuple
            # pylint: disable=locally-disabled, unsubscriptable-object
            template_str = "Embedded Template\n%s" % exception.source[0]

        raise aomi_excep.Validation("Bad template %s" % str(exception),
                                    source=template_str)

    except jinja2.exceptions.UndefinedError as exception:
        template_traces = [x.strip()
                           for x in traceback.format_tb(sys.exc_info()[2])
                           if 'template code' in x]
        raise aomi_excep.Validation("Missing template variable %s" %
                                    ' '.join(template_traces))
727368
def main():
    """"""
    data = Common.open_file(F_INFO)
    config = Common.open_file(F_CONFIG)
    file_full_path = ""

    env = load_jinja2_env(config['p_template'])

    for index, page in data.iteritems():
        logging.info('Creating ' + index + ' page:')

        template = env.get_template(page['f_template'] + \
            config['f_template_ext'])

        for lang, content in page['content'].items():
            if lang == "NaL":
                if page['f_directory'] != '':
                    Common.make_dir(config['p_build'] + page['f_directory'])

                file_full_path = config['p_build'] + page['f_directory'] + \
                    page['f_name'] +page['f_endtype']
            else:
                if page['f_directory'] != '':
                    Common.make_dir(config['p_build'] + lang + '/' + \
                        page['f_directory'])

                file_full_path = config['p_build'] + lang + '/' + \
                    page['f_directory'] + page['f_name'] +page['f_endtype']

            with open(file_full_path, 'w') as target_file:
                target_file.write(template.render(content))

        logging.info('Page ' + index + ' created.')
288702
def get_template(path,
                 dest,
                 template='jinja',
                 saltenv='base',
                 makedirs=False,
                 **kwargs):
    '''
    
    '''
    if 'salt' not in kwargs:
        kwargs['salt'] = __salt__
    if 'pillar' not in kwargs:
        kwargs['pillar'] = __pillar__
    if 'grains' not in kwargs:
        kwargs['grains'] = __grains__
    if 'opts' not in kwargs:
        kwargs['opts'] = __opts__
    return _client().get_template(
            path,
            dest,
            template,
            makedirs,
            saltenv,
            **kwargs)
276465
def load_template_source(template_name, template_dirs=None):
    """"""
    template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", [])

    # Try each ZIP file in TEMPLATE_ZIP_FILES.
    for fname in template_zipfiles:
        try:
            z = zipfile.ZipFile(fname)
            source = z.read(template_name)
        except (IOError, KeyError):
            continue
        z.close()
        # We found a template, so return the source.
        template_path = "%s:%s" % (fname, template_name)
        return (source, template_path)

    # If we reach here, the template couldn't be loaded
    raise TemplateDoesNotExist(template_name)
244795
async def render_template_string(source: str, **context: Any) -> str:
    
    await current_app.update_template_context(context)
    template = current_app.jinja_env.from_string(source)
    return await _render(template, context)
866587
def setup(self, app):
        """"""
        super(Plugin, self).setup(app)

        if 'jinja2' not in app.plugins:
            raise PluginException('The plugin requires Muffin-Jinja2 plugin installed.')

        self.cfg.prefix = self.cfg.prefix.rstrip('/') + '/'
        self.cfg.exclude.append(self.cfg.prefix)

        # Setup debugtoolbar templates
        app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, 'templates'))

        self.cfg.panels += list(self.cfg.additional_panels)
        panels_ = []
        for panel in self.cfg.panels:
            if isinstance(panel, str):
                mod, _, panel = panel.partition(':')
                mod = importlib.import_module(mod)
                panel = eval(panel or 'DebugPanel', mod.__dict__)
            panels_.append(panel)
        self.cfg.panels = panels_

        # Setup debugtoolbar static files
        app.router.register_route(StaticRoute(
            'debugtoolbar.static',
            self.cfg.prefix + 'static/',
            op.join(PLUGIN_ROOT, 'static')))

        app.register(self.cfg.prefix + 'sse', name='debugtoolbar.sse')(self.sse)
        app.register(
            self.cfg.prefix + 'exception', name='debugtoolbar.exception')(self.exception)
        app.register(
            self.cfg.prefix + 'execute', name='debugtoolbar.execute')(self.execute)
        app.register(
            self.cfg.prefix + 'source', name='debugtoolbar.source')(self.source)
        app.register(
            self.cfg.prefix.rstrip('/'),
            self.cfg.prefix,
            self.cfg.prefix + '{request_id}', name='debugtoolbar.request')(self.view)

        app['debugtoolbar'] = {}
        app['debugtoolbar']['pdbt_token'] = uuid.uuid4().hex
        self.history = app['debugtoolbar']['history'] = utils.History(50)
        self.exceptions = app['debugtoolbar']['exceptions'] = utils.History(50)
        self.frames = app['debugtoolbar']['frames'] = utils.History(100)
153658
def load_default_templates(self):
        """"""
        for importer, modname, is_pkg in pkgutil.iter_modules(templates.__path__):
            self.register_template('.'.join((templates.__name__, modname)))
1285043
def _get_template(self):
        
        loader = PackageLoader(self._package_name, 'assets/templates')
        env = Environment(extensions=['jinja2.ext.with_'], loader=loader)
        return env.get_template('{}.html'.format(self._report_name))
1004003
def add_path_to_jinja(flask_app, path):
    
    template_dir = path
    my_loader = jinja2.ChoiceLoader([
        flask_app.jinja_loader,
        jinja2.FileSystemLoader(template_dir)
    ])
    flask_app.jinja_loader = my_loader
733510
private final CompiledST loadTemplateResource(String prefix, String unqualifiedFileName) {
        //if (resourceRoot == null) return null;
        //return loadTemplate(resourceRoot, prefix, unqualifiedFileName);
        if (resourceRoots.isEmpty()) return null;
        CompiledST template = null;
        for (URL resourceRoot : resourceRoots) {
            if ((template = loadTemplate(resourceRoot, prefix, unqualifiedFileName)) != null)
                return template;
        }
        return null;
    }