def setup(self): # Setup the assets environment. assets_env = AssetsEnvironment('', '') self.foo_bundle = Bundle() self.bar_bundle = Bundle() assets_env.register('foo_bundle', self.foo_bundle) assets_env.register('bar_bundle', self.bar_bundle) # Inject a mock bundle class into the Jinja2 extension, so we # can check on what exactly it does. test_instance = self class MockBundle(Bundle): urls_to_fake = ['foo'] def __init__(self, *a, **kw): Bundle.__init__(self, *a, **kw) self.env = assets_env # Kind of hacky, but gives us access to the last Bundle # instance used by the extension. test_instance.the_bundle = self def urls(self, *a, **kw): return self.urls_to_fake self._old_bundle_class = AssetsExtension.BundleClass AssetsExtension.BundleClass = self.BundleClass = MockBundle # Setup the Jinja2 environment. self.jinja_env = JinjaEnvironment() self.jinja_env.add_extension(AssetsExtension) self.jinja_env.assets_environment = assets_env
def __init__(self, name, at_path, additional_paths=None): self.name = name self.path = at_path # non-theme folders that can use the jinja2 Environment in Theme object if not additional_paths: additional_paths = [] if not isinstance(additional_paths, list): additional_paths = [additional_paths] self.additional_paths = additional_paths # the parts of a theme-pack self.collection_points = { 'pieces': (os.path.join(self.path, 'pieces'), Theme.pieces_regex), 'styles': (os.path.join(self.path, 'assets', 'css'), Theme.styles_regex), 'scripts': (os.path.join(self.path, 'assets', 'js'), Theme.scripts_regex), 'images': (os.path.join(self.path, 'assets', 'img'), Theme.images_regex) } self.collected_items = {} for ftype, identity in self.collection_points.items(): self.collected_items[ftype] = generic_collect( identity[0], identity[1], ftype, ThemeFile) self.jinja_environment = self.collection_points['pieces'][ 0] # path the pieces folder self.additional_paths.append(self.jinja_environment) self.jinja_environment = JinjaEnvironment( loader=JinjaLoader(self.additional_paths), cache_size=Globals.JINJA_CACHE_FILES)
def __init__(self): super().__init__() self._environment = JinjaEnvironment(loader=JinjaPackageLoader( __package__, "templates"), trim_blocks=True, keep_trailing_newline=True) self._template = self._environment.get_template("root.json")
def html_report(datasets, mem_type='WorkingSetPrivate', mem_unit='KB',\ output_path='out.html', pools_to_monitor=None, top_txt=None, bot_txt=None): """ produces an html report datasets: the data to plot along with labels mem_type: (optional) what type of memory you'd like to monitor mem_unit: (optional) the memory units output_path: where to save the html report """ if pools_to_monitor: datasets = dict((k,v) for k, v in datasets.items() if k in pools_to_monitor) datasets = dict((str(k),v) for k, v in datasets.items()) for val in datasets.values(): if 'label' in val: val['label'] = str(val['label']) context = { 'datasets': datasets, 'xlabel': 'time (seconds)', 'ylabel': '%s (%s)' % (mem_type, mem_unit), 'top_txt': top_txt, 'bot_txt': bot_txt } source = open(TEMPLATE_FILE, 'r').read() jinja_template = JinjaEnvironment().from_string(source) out = jinja_template.render(context) out_file = open(output_path, 'w') out_file.write(out) out_file.close() print("The html report is saved to %s" % os.path.realpath(output_path))
def __init__(self, config: Config, key: str) -> None: self._loader = ConfigTemplateLoader(config, key) self._env = JinjaEnvironment(loader=self._loader, lstrip_blocks=True, trim_blocks=True, extensions=["jinja2.ext.do"]) self._env.filters["markdown"] = markdown.render
def create(self): ''' Returns nothing. Write gathered posts/pages to build directory @todo use post.py's Post() ''' self.env = JinjaEnvironment(loader=FileSystemLoader(self.template_dir)) self.sort_posts() # sorts in place for post in self.posts: # destination is .html # ./content/formatted/post1.html post_file_dir = format_output_path(self.posts_dest_dir, post['filename'], '.html') # content/posts with codecs.open(post_file_dir, 'w') as outfile: outfile.write(self.create_post(post)) print('Wrote %s posts' % len(self.posts)) with codecs.open(os.path.join(self.output_dir, 'index.html'), 'w', encoding='utf8') as indexfile: indexfile.write(self.create_index(self.posts)) # @todo create a 'pages' task print('Site Build Complete')
def __init__(self, main_path, **std_args): self.std_args = std_args self.main_path = abspath(main_path) self.debug = self.std_args.get('debug', True) self.logger = globby.logger.Logger(join(self.main_path, 'logs'), self.debug) self.project = ProjectEnvironment( self.main_path, self.std_args.get('project', 'documentation'), 'projects', self.std_args.get('suffix', 'txt'), ) self.theme = ThemeEnvironment( self.main_path, self.std_args.get('theme', 'default'), 'themes', self.std_args.get('template_suffix', 'tmpl')) self.jinja_env = JinjaEnvironment(loader=self.theme) #XXX clearify `charset` self.charset = self.std_args.get('charset', 'utf-8') self.accept_all = self.std_args.get('accept_all', False) self.pygments_style = self.std_args.get('pygments_style', 'default') self.builder_dct = dict([ (x.name, x) for x in Unit.get_all(globby.builder.Builder) ]) self.builder = self.builder_dct[self.std_args.get( 'builder', 'project2html')] processors = globby.markup.get_all_processors()[1] self.markup_processor = processors[self.std_args.get( 'markup_processor', 'woxt')] self.template_context = { 'markup_processor': self.markup_processor, 'suffix': self.project.suffix, 'theme': self.theme.name, 'debug': self.debug, 'project': self.project.name, 'charset': self.charset, 'main_path': self.main_path, 'projects_path': self.project.projects_path, 'themes_path': self.theme.themes_path, 'copyright': ('This page was generated with ' '<a href="http://globby.webshox.org">Globby</a>'), } self.css_data = {}
def display_as_markdown(entries, md_filename): jinja_templateEnv = JinjaEnvironment(loader=FileSystemLoader('templates/')) TEMPLATE_FILE = 'template_bibtex.md.jinja' jinja_template = jinja_templateEnv.get_template(TEMPLATE_FILE) with codecs.open(md_filename, mode='w', encoding='utf-8') as md_file: md_file.write( jinja_template.render( {'entries': entries} ) )
def jinja_render(template, context): """Render a Jinja template. Arguments: template (str): The Jinja template string. context (Dict[str, obj]): A dictionary of variables for Jinja. Returns: str: The rendered string. """ return JinjaEnvironment().from_string(template).render(**context)
def __init__(self, name, extra_imports=[], **kwargs): """ @param kwargs: Additional variables passed to template """ super(Template, self).__init__(name) params = self.env.config.params variables = checked_unite(params, kwargs) self.imports_dict = dict((module.__name__, module) for module in extra_imports) self.context = variables.copy() if variables else {} if not hasattr(self, 'template_env'): self.template_env = JinjaEnvironment(loader=TemplateLoader(self.env), autoescape=False, undefined=StrictUndefined, trim_blocks=True) self.template = self.template_env.get_template(self.name)
def initialize(self): loader = FileSystemLoader([ self.settings['template_path'], self.settings['snippet_path']]) assets_env = AssetsEnvironment(self.settings['static_path'], self.static_url('')) register_filter(LibSass) self.template_env = JinjaEnvironment( loader=loader, extensions=[AssetsExtension]) self.template_env.assets_environment = assets_env self.template_env.filters['stylesheet_tag'] = self.stylesheet_tag self.template_env.filters['javascript_tag'] = self.javascript_tag self.template_env.filters['theme_image_url'] = self.theme_image_url self.template_env.globals = self.get_globals() self.site = self.settings['site']
async def start(self) -> None: self.client.add_dispatcher(MembershipEventDispatcher) self.config.load_and_update() self.load_simple_vars() loader = ConfigTemplateLoader(self.config) self.jinja_env = JinjaEnvironment(loader=loader) base = declarative_base(cls=BaseClass, bind=self.database) self.case = Case.copy(bind=self.database, rebase=base) self.control_event = ControlEvent.copy(bind=self.database, rebase=base) self.case_accept = CaseAccept.copy(bind=self.database, rebase=base) base.metadata.create_all() await self.update_agents()
def parse_jinja_template(path, context): """Parse a Jinja 2 template. :param path: Path to the template. :type path: str :param context: The context to be parsed into the template. :type context: dict :rtype: str """ search_path = os.path.dirname(path) env = JinjaEnvironment(loader=FileSystemLoader(search_path)) template_name = os.path.basename(path) template = env.get_template(template_name) return template.render(**context)
def generator_one_table(table_name, table): context = {'name': table_name, 'table': table} source = """\ #!/usr/bin/python from sqlalchemy import Column, ForeignKey, Integer, String, create_engine from sqlalchemy.orm import sessionmaker DB_CONNECT_STRING = 'mysql+mysqldb://root:[email protected]/nova?charset=utf8' #engine = create_engine(DB_CONNECT_STRING, echo=True) engine = create_engine(DB_CONNECT_STRING, echo=False) DB_Session = sessionmaker(bind=engine) session = DB_Session() for row in session.execute('select * from ${name} ;').fetchall(): row=dict(zip(row.keys(), row.values())); % for cell in table ${cell}=row["${cell}"]+"_${cell}_data"; % endfor session.execute("insert into ${name} values( \\ % for cell in table '${cell}', \\ % endfor )"); session.commit(); \ """ jinja_template = JinjaEnvironment( line_statement_prefix='%', variable_start_string="${", variable_end_string="}").from_string(source) #print jinja_template.environment.compile(source, raw=True) str = jinja_template.render(context) if not os.path.isdir("data/"): os.mkdir("data/") f = open("data/%s.py" % table_name, "w") f.write("%s" % str) f.close()
def gen_front(): last = new_code() - 1 start = last - 100 if start < 0 : start = 0 topcs = [get_FNSRecord(x) for x in range(start, last+1)] topcs.reverse() env = JinjaEnvironment( loader=JinjaFileSystemLoader( os.path.join( LOCAL, "program" ) ) ) env.filters['dtstring'] = dtstring tmpl = env.get_template("FRONT.tmpl.html") gen = tmpl.render(topcs=topcs) open(os.path.join(LOCAL, "index.html"), 'w', encoding="utf-8").write(gen) nlines = len(gen.splitlines()) print("Gen index.html done. (%d lines)" % nlines)
from nornir.core.filter import F from nornir.core.plugins.inventory import InventoryPluginRegister from jinja2 import Environment as JinjaEnvironment from cnaas_nms.confpush.nornir_plugins.cnaas_inventory import CnaasInventory from cnaas_nms.scheduler.jobresult import JobResult @dataclass class NornirJobResult(JobResult): nrresult: Optional[MultiResult] = None change_score: Optional[float] = None cnaas_jinja_env = JinjaEnvironment(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True) def cnaas_init() -> Nornir: InventoryPluginRegister.register("CnaasInventory", CnaasInventory) nr = InitNornir(runner={ "plugin": "threaded", "options": { "num_workers": 50 } }, inventory={"plugin": "CnaasInventory"}, logging={ "log_file": "/tmp/nornir-pid{}.log".format(os.getpid()),
if opt == "-h": print('-i <inputfile> -o [outputfile] -t [template]') print('or: -input <inputfile> --output [outputfile] --tmpl [template]') exit() elif opt in ('-i', '--input'): input_file = arg elif opt in ('-o', '--output'): output_file = arg elif opt in ('-t', '--template'): template = arg if input_file and not output_file: output_file = os.path.dirname(input_file) + '/Router.Generate.swift' if not input_file or not output_file: print('miss input file: -i <inputfile> or: -input <inputfile>') print('') return (input_file, output_file, template) if __name__ == '__main__': input_file, output_file, template = parse_args() with open(input_file, 'r', encoding='utf-8') as f1, open(output_file, 'wt') as f2: text = f1.read() env = JinjaEnvironment(line_statement_prefix="#", loader=FileSystemLoader(searchpath=['./tmpl', 'Pods/RGenerator/tmpl'])) tmpl = env.get_template(template) models = [(item.name, item.case_models, item.has_no_parameter_case) for item in parse_file(text)] text = tmpl.render(models=models, snake_to_camel=snake_to_camel) f2.write(text)
jinja_template = JinjaEnvironment( line_statement_prefix='%', variable_start_string="${", variable_end_string="}" ).from_string("""\ <!doctype html> <html> <head> <title>${page_title|e}</title> </head> <body> <div class="header"> <h1>${page_title|e}</h1> </div> <ul class="navigation"> % for href, caption in [ ('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products') ] <li><a href="${href|e}">${caption|e}</a></li> % endfor </ul> <div class="table"> <table> % for row in table <tr> % for cell in row <td>${cell}</td> % endfor </tr> % endfor </table> </div> </body> </html>\ """)
elif opt in ('-i', '--input'): input_file = arg elif opt in ('-o', '--output'): output_path = arg elif opt in ('-t', '--template'): template = arg if input_file and not output_path: output_path = os.path.dirname(input_file) if not input_file or not output_path: print('miss input file: -i <inputfile> or: -input <inputfile>') print('') return (input_file, output_path, template) if __name__ == '__main__': input_file, output_path, template = parse_args() all_entity = parse_model(input_file) for entity in all_entity: output_name = output_path + entity.name + '+CoreDataProperties.swift' with open(output_name, 'wt') as f2: env = JinjaEnvironment(line_statement_prefix="#", loader=FileSystemLoader(searchpath=['./'])) tmpl = env.get_template(template) text = tmpl.render(entity=entity) f2.write(text) print('generated ' + output_name)
<title>${page_title|e}</title> </head> <body> <div class="header"> <h1>${page_title|e}</h1> </div> <div class="table"> <table> % for row in table <tr> % for cell in row <td>${testmacro(cell)}</td> % endfor </tr> % endfor </table> </div> </body> </html>\ """ jinja_template = JinjaEnvironment(line_statement_prefix='%', variable_start_string="${", variable_end_string="}").from_string(source) print(jinja_template.environment.compile(source, raw=True)) p = Profile() p.runcall(lambda: jinja_template.render(context)) stats = Stats(p) stats.sort_stats('time', 'calls') stats.print_stats()
def setup(self): TempEnvironmentHelper.setup(self) self.jinja_env = JinjaEnvironment() self.jinja_env.add_extension(AssetsExtension) self.jinja_env.assets_environment = self.env
import logging logger = logging.getLogger(__name__) from jinja2 import ( Template as JinjaTemplate, Environment as JinjaEnvironment, FunctionLoader, ) from datetime import datetime, timedelta from django.db import models from .utils import ( send_to_iterable, ) iterableEnviron = JinjaEnvironment( variable_start_string="[[", variable_end_string="]]", loader=FunctionLoader(lambda tmpl_name: Component.objects.get( name=tmpl_name).load_template()), ) RENDER_MARKDOWN = mistune.Markdown() MARKDOWN = 'markdown' YAML = 'yaml' HTML = 'htmlmixed' DJANGO = 'django' MJML = 'mjml' ITERABLE = 'iterable' #iterable snippet """ Template Header content=[{block1}] Body
def __init__(self, name, extra_imports=[], **kwargs): self.template_env = JinjaEnvironment(loader=FunctionLoader(lambda text: text)) super(InlineTemplate, self).__init__(name, extra_imports, **kwargs)