Loads the jinja2 HTML template from the given file.
    Assumes that the file is in the same directory as the script.
492712
def load_jinja_template(file_name):
    
    original_script_path = sys.argv[0]
    #script_path = os.path.dirname(os.path.realpath(__file__))
    script_dir = os.path.dirname(original_script_path)
    # file_path = os.path.join(script_path, file_name)
    # with open(file_path, 'r') as template_file:
    #     return template_file.read()
    from jinja2 import Environment, FileSystemLoader

    env = Environment(loader=FileSystemLoader(script_dir))
    template = env.get_template(file_name)

    return template
938310
def create_jinja_env():
    
    template_dir = os.path.join(os.path.dirname(__file__), 'templates')
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_dir),
        autoescape=jinja2.select_autoescape(['html'])
    )
    env.filters['simple_date'] = filter_simple_date
    env.filters['paragraphify'] = filter_paragraphify
    return env
81637
def render_template(self, source, **kwargs_context):
        
        """
        return self.jinja_env.from_string(source).render(kwargs_context)
939844
def stream_template(template_name, **context):
    '''
    
    '''
    app.update_template_context(context)
    template = app.jinja_env.get_template(template_name)
    stream = template.generate(context)
    return Response(stream_with_context(stream))
694356
def convert(self):
        
        # move file into position
        try:
            local_file = self.getter.get()
        except (exceptions.NoSuchPackageException, OSError) as e:
            logger.error(
                "Failed and exiting:", exc_info=True)
            logger.info("Pyp2rpm failed. See log for more info.")

            sys.exit(e)

        # save name and version from the file (rewrite if set previously)
        self.name, self.version = self.getter.get_name_version()

        self.local_file = local_file
        data = self.metadata_extractor.extract_data(self.client)
        logger.debug("Extracted metadata:")
        logger.debug(pprint.pformat(data.data))
        self.merge_versions(data)

        jinja_env = jinja2.Environment(loader=jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(['/']),
            jinja2.PackageLoader('pyp2rpm', 'templates'), ]))

        for filter in filters.__all__:
            jinja_env.filters[filter.__name__] = filter

        try:
            jinja_template = jinja_env.get_template(
                os.path.abspath(self.template))
        except jinja2.exceptions.TemplateNotFound:
            # absolute path not found => search in default template dir
            logger.warn('Template: {0} was not found in {1} using default '
                        'template dir.'.format(
                            self.template, os.path.abspath(self.template)))

            jinja_template = jinja_env.get_template(self.template)
            logger.info('Using default template: {0}.'.format(self.template))

        ret = jinja_template.render(data=data, name_convertor=name_convertor)
        return re.sub(r'[ \t]+\n', "\n", ret)
858746
def load
      @load_time = Time.now
      @meta = {}
      if template?
        logger.debug "loading #{path}"
        file.open do |io|
          read_meta(io)
          @template_start_line = io.lineno + 1
          @template_text = io.read
        end
      end
    end
895921
def template_content
      if File.file?(@template_file) && File.readable?(@template_file)
        return File.read(@template_file)
      end

      raise ArgumentError, _("'%{template}' is not a readable file") % { template: @template_file }
    end
524973
def _compile(self, source, filename):
        
        if filename == '<template>':
            # make a better filename
            filename = 'dbt-{}'.format(
                codecs.encode(os.urandom(12), 'hex').decode('ascii')
            )
            # encode, though I don't think this matters
            filename = jinja2._compat.encode_filename(filename)
            # put ourselves in the cache
            linecache.cache[filename] = (
                len(source),
                None,
                [line + '\n' for line in source.splitlines()],
                filename
            )

        return super(MacroFuzzEnvironment, self)._compile(source, filename)
515802
def load(self, name):
        

        if self.reload:
            self._maybe_purge_cache()

        template = self.cache.get(name)
        if template:
            return template

        path = self.resolve(name)
        if not path:
            raise OSError(errno.ENOENT, "File not found: %s" % name)

        with codecs.open(path, 'r', encoding='UTF-8') as f:
            contents = f.read()
            mtime = os.fstat(f.fileno()).st_mtime

        template = self.load_string(contents, filename=path)
        template.mtime = mtime
        template.path = path

        self.cache[name] = template
        return template
648148
def add_template_dirs(app):
    
    template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')

    app.jinja_loader = jinja2.ChoiceLoader(
        [app.jinja_loader, jinja2.FileSystemLoader(template_dir)]
    )
602578
def setup(self, app):
        
        super().setup(app)

        if isinstance(self.cfg.template_folders, str):
            self.cfg.template_folders = [self.cfg.template_folders]

        self.cfg.template_folders = list(self.cfg.template_folders)
        if not self.cfg.loader:
            self.cfg.loader = FileSystemLoader(
                self.cfg.template_folders, encoding=self.cfg.encoding)

        self.env = jinja2.Environment(
            auto_reload=self.cfg.auto_reload,
            cache_size=self.cfg.cache_size,
            extensions=self.cfg.extensions,
            loader=self.cfg.loader,
        )
        self.env.globals['app'] = app

        @self.register
        @jinja2.contextfunction
        def debug(ctx, value=None):
            """ Debug current context to template. """
            return jinja2.filters.do_pprint(value is None and ctx or value)

        @self.filter
        def jsonify(obj):
            return dumps(obj, ensure_ascii=False, encode_html_chars=True)
1362261
def template_from_file(basedir, path, vars):
    '''  '''

    from cirruscluster.ext.ansible import utils
    realpath = utils.path_dwim(basedir, path)
    loader=jinja2.FileSystemLoader([basedir,os.path.dirname(realpath)])
    environment = jinja2.Environment(loader=loader, trim_blocks=True)
    for filter_plugin in utils.plugins.filter_loader.all():
        filters = filter_plugin.filters()
        if not isinstance(filters, dict):
            raise errors.AnsibleError("FilterModule.filters should return a dict.")
        environment.filters.update(filters)
    try:
        data = codecs.open(realpath, encoding="utf8").read()
    except UnicodeDecodeError:
        raise errors.AnsibleError("unable to process as utf-8: %s" % realpath)
    except:
        raise errors.AnsibleError("unable to read %s" % realpath)

    # Get jinja env overrides from template
    if data.startswith(JINJA2_OVERRIDE):
        eol = data.find('\n')
        line = data[len(JINJA2_OVERRIDE):eol]
        data = data[eol+1:]
        for pair in line.split(','):
            (key,val) = pair.split(':')
            setattr(environment,key.strip(),val.strip())

    environment.template_class = J2Template
    t = environment.from_string(data)
    vars = vars.copy()
    try:
        template_uid = pwd.getpwuid(os.stat(realpath).st_uid).pw_name
    except:
        template_uid = os.stat(realpath).st_uid
    vars['template_host']   = os.uname()[1]
    vars['template_path']   = realpath
    vars['template_mtime']  = datetime.datetime.fromtimestamp(os.path.getmtime(realpath))
    vars['template_uid']    = template_uid
    vars['template_fullpath'] = os.path.abspath(realpath)
    vars['template_run_date'] = datetime.datetime.now()

    managed_default = C.DEFAULT_MANAGED_STR
    managed_str = managed_default.format(
                    host = vars['template_host'],
                    uid  = vars['template_uid'],
                    file = vars['template_path']
                    )
    vars['ansible_managed'] = time.strftime(managed_str,
                                time.localtime(os.path.getmtime(realpath)))

    # This line performs deep Jinja2 magic that uses the _jinja2_vars object for vars
    # Ideally, this could use some API where setting shared=True and the object won't get
    # passed through dict(o), but I have not found that yet.
    res = jinja2.utils.concat(t.root_render_func(t.new_context(_jinja2_vars(basedir, vars, t.globals), shared=True)))

    if data.endswith('\n') and not res.endswith('\n'):
        res = res + '\n'
    return template(basedir, res, vars)
63071
def _print_html(self):
        
        cur_path = os.path.dirname(os.path.realpath(sys.argv[0]))
        shutil.copytree(cur_path+'webpage/template/', '')
684060
def template(self, template_filename, **kwargs):
        
        template = renderer.get_template(template_filename)
        kwargs["gns3_version"] = __version__
        kwargs["gns3_host"] = self._request.host
        self.html(template.render(**kwargs))
962604
function loadJsFile(file) {
    var modId = path.basename(file).slice(0, -3);
    var mod = require(file);
    modulePath[modId] = file;
    mod.__id = modId;
    return mod;
}
318878
def _load(self, reload=False):
        
        if self.autoreload or reload:
            # First, we load from YAML, failing if syntax errors are found
            options = self.storage_options or {}
            if hasattr(self.path, 'path') or hasattr(self.path, 'read'):
                file_open = self.path
                self.path = make_path_posix(
                    getattr(self.path, 'path',
                            getattr(self.path, 'name', 'file')))
            else:
                file_open = open_files(self.path, mode='rb', **options)
                assert len(file_open) == 1
                file_open = file_open[0]
            self._dir = get_dir(self.path)

            with file_open as f:
                text = f.read().decode()
            if "!template " in text:
                logger.warning("Use of '!template' deprecated - fixing")
                text = text.replace('!template ', '')
            self.parse(text)
1303412
def load(cls, file):
        
        d = json.load(file)
        return cls.create(d)