本文整理汇总了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)
示例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
示例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)
示例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')
示例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)
示例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
示例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
示例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
示例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
示例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)
示例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)
示例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
示例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)
示例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())
示例15: get_template
def get_template(self, name):
loader = FileSystemLoader(os.getcwd())
return loader.load(self.settings['jinja2_env'], name)