當前位置: 首頁>>代碼示例>>Python>>正文


Python jinja2.FileSystemLoader類代碼示例

本文整理匯總了Python中jinja2.FileSystemLoader的典型用法代碼示例。如果您正苦於以下問題:Python FileSystemLoader類的具體用法?Python FileSystemLoader怎麽用?Python FileSystemLoader使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了FileSystemLoader類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: templated_file_contents

def templated_file_contents(options, configfile):
    paths = options["searchpath"].split(",") # CSV of PATHs
    if os.path.isdir(paths[0]):
        loader = FileSystemLoader(paths)
    else:
        loader = URLloader(paths)
    env = Environment(loader=loader)
    contents, config_full_path, _a_lambda_ = loader.get_source(env, configfile)
    template = env.from_string(contents, globals=options)
    return template.render(options)
開發者ID:sglebs,項目名稱:ndeploy,代碼行數:10,代碼來源:ndeploy.py

示例2: _get_nereid_template_messages_from_file

 def _get_nereid_template_messages_from_file(self, template_dir, template):
     """
     Same generator as _get_nereid_template_messages, but for specific files.
     """
     extract_options = self._get_nereid_template_extract_options()
     loader = FileSystemLoader(template_dir)
     file_obj = open(loader.get_source({}, template)[1])
     for message_tuple in babel_extract(
             file_obj, GETTEXT_FUNCTIONS,
             ['trans:'], extract_options):
         yield (template,) + message_tuple
開發者ID:priyankajain18,項目名稱:nereid,代碼行數:11,代碼來源:translation.py

示例3: to_html

 def to_html(self, embed_css=True):
     import os
     from jinja2 import Environment, FileSystemLoader
     loader = FileSystemLoader(
         os.path.join(os.path.dirname(os.path.abspath(__file__)), 'html'))
     env = Environment(loader=loader)
     template = env.get_template('template.html')
     return template.render(rulesets=self.rulesets,
         lines=self.lines,
         text=self.text,
         css=loader.get_source(env, 'style.css')[0] if embed_css else None)
開發者ID:bhattisatish,項目名稱:WritingSmellDetector,代碼行數:11,代碼來源:wsd.py

示例4: generate_manifests

def generate_manifests(path, kwargs, pkg_name):
    click.echo('Generate manifest')
    loader = FileSystemLoader(path)
    env = Environment(loader=loader)
    out = os.path.join(ROOT_PATH, 'kubernetes')
    for name in loader.list_templates():
        template = env.get_template(name)
        fname = os.path.join(out, name.replace('.j2', ''))
        with open(fname, 'w') as f:
            f.write(template.render(**kwargs))
    with tarfile.open(pkg_name, "w:gz") as tar:
        tar.add(out, arcname='kube-admin')
開發者ID:holandes22,項目名稱:kube-admin,代碼行數:12,代碼來源:cli.py

示例5: render_pages

def render_pages():
    loader = FileSystemLoader('source')
    env = Environment(loader=loader)

    for name in loader.list_templates():
        if name.startswith('_'):
            continue

        template = env.get_template(name)
        print "writing {}".format(name)
        with open(name, 'w') as handle:
            output = template.render()
            handle.write(output)
開發者ID:nameko,項目名稱:nameko.github.io,代碼行數:13,代碼來源:build.py

示例6: TemplateService

class TemplateService(EngineService):
    endpoint_methods = None
    published_members = ['render', 'get_base_templates', 'render_from_string', 'get_source']
    name = 'template'
    # Project's base path
    __base_path = os.path.dirname(os.path.realpath(__file__))
    # User's application base path
    __app_base_path = None
    __app_base_templates_dir = None
    # Our internal jinja2 template env
    __template_env = None
    __fs_loader = None

    def __init__(self, engine):

        super(TemplateService, self).__init__(engine)

        self.__app_base_path = self.engine.get('csettings', 'all')()['templates_root']
        self.__app_base_templates_dir = self.engine.get('csettings', 'all')()['base_templates_dir']

        self.__fs_loader = FileSystemLoader(
            # Search path gets saved as a list in jinja2 internally, so we could
            # add to it if necessary.
            searchpath=[self.__base_path + '/templates', self.__app_base_path],
            encoding='utf-8',
        )
        self.__template_env = Environment(loader=self.__fs_loader, trim_blocks=True)

    def render(self, template_name, context):
        """
        Context must be a dictionary right now, but could also be **kwargs
        """
        # Add the global corus settings from engine to the context
        context['csettings'] = self.engine.get('csettings', 'all')()
        return self.__template_env.get_template(template_name).render(context)

    def render_from_string(self, s, context):
        # TODO we should probably make a new loader for getting stuff out of NDB
        return self.__template_env.from_string(s).render(context)

    def get_base_templates(self):
        # The call to FS loader list_templates is a sorted set, so just append, return
        bts = []
        for t in self.__fs_loader.list_templates():
            if t.startswith(self.__app_base_templates_dir):
                bts.append(t)
        return bts

    def get_source(self, template_name):
        source, filename, uptodate = self.__fs_loader.get_source(self.__template_env, template_name)
        return source
開發者ID:wrunk,項目名稱:corus,代碼行數:51,代碼來源:template.py

示例7: _get_nereid_template_messages

    def _get_nereid_template_messages(cls):
        """
        Extract localizable strings from the templates of installed modules.

        For every string found this function yields a
        `(module, template, lineno, function, message)` tuple, where:

        * module is the name of the module in which the template is found
        * template is the name of the template in which message was found
        * lineno is the number of the line on which the string was found,
        * function is the name of the gettext function used (if the string
          was extracted from embedded Python code), and
        * message is the string itself (a unicode object, or a tuple of
          unicode objects for functions with multiple string arguments).
        * comments List of Translation comments if any. Comments in the code
          should have a prefix `trans:`. Example::

              {{ _(Welcome) }} {# trans: In the top banner #}
        """
        extract_options = cls._get_nereid_template_extract_options()
        logger = logging.getLogger('nereid.translation')

        for module, directory in cls._get_installed_module_directories():
            template_dir = os.path.join(directory, 'templates')
            if not os.path.isdir(template_dir):
                # The template directory does not exist. Just continue
                continue

            logger.info(
                'Found template directory for module %s at %s' % (
                    module, template_dir
                )
            )
            # now that there is a template directory, load the templates
            # using a simple filesystem loader and load all the
            # translations from it.
            loader = FileSystemLoader(template_dir)
            env = Environment(loader=loader)
            extensions = '.html,.jinja'
            for template in env.list_templates(extensions=extensions):
                logger.info('Loading from: %s:%s' % (module, template))
                file_obj = open(loader.get_source({}, template)[1])
                for message_tuple in babel_extract(
                        file_obj, GETTEXT_FUNCTIONS,
                        ['trans:'], extract_options):
                    yield (module, template) + message_tuple
開發者ID:priyankajain18,項目名稱:nereid,代碼行數:46,代碼來源:translation.py

示例8: _clean_nereid_template

    def _clean_nereid_template(translation):
        """
        Clean the template translations if the module is not installed, or if
        the template is not there.
        """
        TranslationSet = Pool().get('ir.translation.set', type='wizard')
        installed_modules = TranslationSet._get_installed_module_directories()

        # Clean if the module is not installed anymore
        for module, directory in installed_modules:
            if translation.module == module:
                break
        else:
            return True

        # Clean if the template directory does not exist
        template_dir = os.path.join(directory, 'templates')
        if not os.path.isdir(template_dir):
            return True

        # Clean if the template is not found
        loader = FileSystemLoader(template_dir)
        if translation.name not in loader.list_templates():
            return True

        # Clean if the translation has changed (avoid duplicates)
        # (translation has no equivalent in template)
        found = False
        for template, lineno, function, message, comments in \
            TranslationSet._get_nereid_template_messages_from_file(
                TranslationSet, template_dir, translation.name):
            if (template, lineno, message, comments and
                    '\n'.join(comments) or None) == \
                (translation.name, translation.res_id, translation.src,
                    translation.comments):
                found = True
                break
        if not found:
            return True
開發者ID:priyankajain18,項目名稱:nereid,代碼行數:39,代碼來源:translation.py

示例9: main

def main():

    env = Environment()
    loader = FileSystemLoader(project_path)

    template_opf = loader.load(env, opf_file)
    template_ncx = loader.load(env, ncx_file)
    #print template_opf.render(name='noisy')

    #ctx = Context(loadContext());

    #d = {'unique_identifier':'test', 'dc_title':'title_test', 'dc_lang':'lang_test'}
    d = loadContext()

    ctx = Context(env, blocks=d, name=opf_file, parent=env.globals)

    template_opf.stream(**d).dump(project_path+'ekundelek_gen.opf')                            #unique_identifier='test', dc_title='title_test', dc_lang='lang_test') #jak dzia?a ** ?
    template_ncx.stream(**d).dump(project_path+'ekundelek_gen.ncx')
    #strim.dump(project_path+'ekundelek_gen.opf')

    print 'Gotowe!'
    pass
開發者ID:pmateja-nexto,項目名稱:kpc,代碼行數:22,代碼來源:run.py

示例10: __init__

    def __init__(self, engine):

        super(TemplateService, self).__init__(engine)

        self.__app_base_path = self.engine.get('csettings', 'all')()['templates_root']
        self.__app_base_templates_dir = self.engine.get('csettings', 'all')()['base_templates_dir']

        self.__fs_loader = FileSystemLoader(
            # Search path gets saved as a list in jinja2 internally, so we could
            # add to it if necessary.
            searchpath=[self.__base_path + '/templates', self.__app_base_path],
            encoding='utf-8',
        )
        self.__template_env = Environment(loader=self.__fs_loader, trim_blocks=True)
開發者ID:wrunk,項目名稱:corus,代碼行數:14,代碼來源:template.py

示例11: to_html

    def to_html(self, embed_css=True, include_empty=False):
        '''
        Convert results into HTML.
        
        Args:
            embed_css: A boolean indicating whether css should be
                embedded into the HTML code.
            include_empty: A boolean indicating whether empty rulesets,
                rules and patterns should be returned.

        Returns:
            A string of HTML code representing the results.
        '''
        from jinja2 import Environment, FileSystemLoader
        loader = FileSystemLoader(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'html'))
        env = Environment(loader=loader)
        template = env.get_template('template.html')
        return template.render(rulesets=self.rulesets,
            lines=self.lines,
            text=self.text,
            css=loader.get_source(env, 'style.css')[0] if embed_css else None,
            include_empty=include_empty)
開發者ID:utapyngo,項目名稱:WritingSmellDetector,代碼行數:23,代碼來源:wsd.py

示例12: _clean_nereid_template

    def _clean_nereid_template(translation):
        """
        Clean the template translations if the module is not installed, or if
        the template is not there.
        """
        TranslationSet = Pool().get('ir.translation.set', type='wizard')
        installed_modules = TranslationSet._get_installed_module_directories()

        # Clean if the module is not installed anymore
        for module, directory in installed_modules:
            if translation.module == module:
                break
        else:
            return True

        # Clean if the template directory does not exist
        template_dir = os.path.join(directory, 'templates')
        if not os.path.isdir(template_dir):
            return True

        # Clean if the template is not found
        loader = FileSystemLoader(template_dir)
        if translation.name not in loader.list_templates():
            return True
開發者ID:GauravButola,項目名稱:nereid,代碼行數:24,代碼來源:translation.py

示例13: get_source

    def get_source(self, environment, template):
        if LOCAL:
            # during local development, templates are files and we want "uptodate" feature
            return FileSystemLoader.get_source(self, environment, template)

        # on production server template may come from zip file
        for searchpath in self.searchpath:
            filename = os.path.join(searchpath, template)
            contents = universal_read(filename)
            if contents is None:
                continue
            contents = contents.decode(self.encoding)

            def uptodate():
                return True

            return contents, filename, uptodate
        raise TemplateNotFound(template)
開發者ID:binaryage,項目名稱:drydrop,代碼行數:18,代碼來源:jinja_loaders.py

示例14: FileSystemLoader

from jinja2 import Environment, FileSystemLoader

# Load index template.
my_template_path = '/srv/projects/intro_programming/intro_programming/notebooks/my_templates'
my_template_base_path = '/srv/projects/intro_programming/intro_programming/notebooks'
ipython_template_path = '/srv/projects/intro_programming/venv/lib/python3.4/site-packages/IPython/nbconvert/templates/html'

my_loader = FileSystemLoader(
    [my_template_path, my_template_base_path, ipython_template_path])
env = Environment(loader=my_loader)

index_template = my_loader.load(env, 'index.tpl')

# Render template to file.
notebooks_path = '/srv/projects/intro_programming/intro_programming/notebooks/'
filepath = notebooks_path + 'index.html'
with open(filepath, 'w') as f:
    f.write(index_template.render())
開發者ID:DucQuang1,項目名稱:intro_programming,代碼行數:18,代碼來源:build_index.py

示例15: get_template

 def get_template(self, name):
     loader = FileSystemLoader(os.getcwd())
     return loader.load(self.settings['jinja2_env'], name)
開發者ID:Carreau,項目名稱:jupyterlab,代碼行數:3,代碼來源:main.py


注:本文中的jinja2.FileSystemLoader類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。