class FileLoaderTestCase(unittest.TestCase): """ Test the ``FileLoader``. """ def setUp(self): import os.path from wheezy.template.loader import FileLoader curdir = os.path.dirname(__file__) tmpldir = os.path.join(curdir, 'templates') self.loader = FileLoader(directories=[tmpldir]) def test_list_names(self): """ Tests list_names. """ assert ('shared/master.html', 'shared/snippet/script.html', 'tmpl1.html') == self.loader.list_names() def test_load_existing(self): """ Tests load. """ assert '' == self.loader.load('tmpl1.html') def test_load_not_found(self): """ Tests load if the name is not found. """ assert None == self.loader.load('tmpl-x.html') def test_load_not_a_file(self): """ Tests load if the name is not a file. """ assert not self.loader.load('shared/snippet')
def post_setup(self, path=None, name=None): # Post setup hook if path: self.path = path else: self.path = os.path.dirname(inspect.getfile(self.__class__)) if name: self.name = name else: self.name = "%s %s " % (self.default_workspace_category, "Plugin") self.name = name # Plugin personal template engine self.templateEngine = Engine( loader=FileLoader([self.path, os.path.join(utils.scriptdir, 'html')]), extensions=[CoreExtension(), CodeExtension()] ) help_path = os.path.join(self.path, 'readme.html') if os.path.exists(help_path): self.help_tab_html_filename = 'readme.html' else: self.help_tab_html_filename = None
def winrate_app(environ, start_response): status = '200 OK' response_headers = [('Content-type', 'text/html'), ('Cache-Control', 'no-cache'), ('Cache-Control', 'must-revalidate')] start_response(status, response_headers) engine = Engine(loader=FileLoader(['']), extensions=[CoreExtension()]) template = engine.get_template('winrate_template.html') player_wins = winrate.download_current_player_wins() leaderboard = winrate.compute_win_rate_leaderboard(player_wins) ranked_leaderboard = [ (str(index + 1), name, "{:.2f}%".format(probability * 100)) for index, (name, probability) in enumerate(leaderboard) ] preview_leaderboard = "" for rank, name, percentile in ranked_leaderboard[:3]: preview_leaderboard += "{}. {} {} ".format(rank, name, percentile) response_body = template.render({ "preview_leaderboard": preview_leaderboard, "leaderboard": ranked_leaderboard }) yield response_body.encode()
def parse_toplevel_config(self, config): super().parse_toplevel_config(config) if GIFormatter.engine is None: module_path = os.path.dirname(__file__) searchpath = [os.path.join(module_path, "html_templates")] + Formatter.engine.loader.searchpath GIFormatter.engine = Engine( loader=FileLoader(searchpath, encoding='UTF-8'), extensions=[CoreExtension(), CodeExtension()]) GIFormatter.engine.global_vars.update({'e': html.escape})
def generate_source(argsstring, options, version, enums, functions_by_category, passthru, extensions, types, raw_enums): template_pattern = re.compile("(.*).template") # Sort by categories and sort the functions inside the categories functions_by_category = sorted(functions_by_category, key=lambda x: x[0]) functions_by_category = list( map(lambda c: (c[0], sorted(c[1], key=lambda x: x.name)), functions_by_category)) template_namespace = { 'passthru': passthru, 'functions': functions_by_category, 'enums': enums, 'options': options, 'version': version, 'extensions': extensions, 'types': types, 'raw_enums': raw_enums, 'args': argsstring } if not os.path.isdir(options.template_dir): print('%s is not a directory' % options.template_dir) exit(1) if os.path.exists(options.outdir) and not os.path.isdir(options.outdir): print('%s is not a directory' % options.outdir) exit(1) if not os.path.exists(options.outdir): os.mkdir(options.outdir) engine = Engine(loader=FileLoader([options.template_dir]), extensions=[CoreExtension(), CodeExtension()]) generatedFiles = 0 allFiles = 0 for template_path in glob('%s/*.template' % os.path.abspath(options.template_dir)): infile = os.path.basename(template_path) outfile = '%s/%s' % (options.outdir, template_pattern.match(infile).group(1)) template = engine.get_template(infile) allFiles += 1 with open(outfile, 'w') as out: out.write(template.render(template_namespace)) print("Successfully generated %s" % outfile) generatedFiles += 1 print("Generated %d of %d files" % (generatedFiles, allFiles))
def main(name): searchpath = [name] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension(token_start='#')]) engine = Engine(loader=PreprocessLoader(engine), extensions=[CoreExtension()]) engine.global_vars.update({'h': escape}) template = engine.get_template('welcome.html') return template.render
class FileLoaderTestCase(unittest.TestCase): """Test the ``FileLoader``.""" def setUp(self) -> None: self.tmpldir = os.path.dirname(__file__) self.loader = FileLoader(directories=[self.tmpldir]) @patch("os.walk") def test_get_template(self, mock_walk: Mock) -> None: mock_walk.return_value = [ ( self.tmpldir + "/", [".ignore", "shared"], [".ignore", "tmpl1.html"], ), ( self.tmpldir + "/shared", [".ignore", "snippet"], ["master.html", ".ignore"], ), ( self.tmpldir + "/shared/snippet", [".ignore"], [".ignore", "script.html"], ), ] assert ( "shared/master.html", "shared/snippet/script.html", "tmpl1.html", ) == self.loader.list_names() def test_load_existing(self) -> None: """Tests load.""" assert "" == self.loader.load("__init__.py") def test_load_not_found(self) -> None: """Tests load if the name is not found.""" assert not self.loader.load("tmpl-x.html") def test_load_not_a_file(self) -> None: """Tests load if the name is not a file.""" assert not self.loader.load("..")
def build_modo_preview_render_command(pathaliases=None, scenes={}): searchpath = [TEMPLATES] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension()]) template = engine.get_template('modo_preview_render_commands.txt') if pathaliases: for key in pathaliases: '{} "{}"'.format(key, os.path.normpath(pathaliases[key])) return template.render({'pathaliases': pathaliases, 'scenes': scenes})
def build_modo_bash(commands=[], headless="", render_range={}): searchpath = [TEMPLATES] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension()]) template = engine.get_template('modo_batch.sh') return template.render({ 'modo_cl': headless, 'commands': commands, 'render_range': render_range })
def main(argv: typing.Optional[typing.List[str]] = None) -> int: args = parse_args(argv or sys.argv[1:]) if not args: return 2 ts = args.token_start extensions = [CoreExtension(ts), CodeExtension(ts)] extensions.extend(args.extensions) engine = Engine(FileLoader(args.searchpath), extensions) engine.global_vars.update({"h": escape}) t = engine.get_template(args.template) sys.stdout.write(t.render(load_context(args.context))) return 0
def get(self): fortunes = db_session.query(Fortune).all() fortunes.append(Fortune(id=0, message="Additional fortune added at request time.")) fortunes.sort(key=attrgetter("message")) engine = Engine(loader=FileLoader(["views"]), extensions=[CoreExtension()]) template = engine.get_template("fortune.html") for f in fortunes: f.message = bleach.clean(f.message) template_html = template.render({"fortunes": fortunes}) response = HTTPResponse() response.write(template_html) return response
def parse_toplevel_config(self, config): super().parse_toplevel_config(config) if GstFormatter.engine is None: gi_extension_path = gi.__path__[0] searchpath = [ os.path.join(gi_extension_path, "html_templates"), self.__tmpdir.name ] + Formatter.engine.loader.searchpath GstFormatter.engine = Engine( loader=FileLoader(searchpath, encoding='UTF-8'), extensions=[CoreExtension(), CodeExtension()]) GstFormatter.engine.global_vars.update({'e': html.escape})
def build_modo_render_command_win(pathaliases=None, scenes={}): searchpath = [TEMPLATES] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension()]) template = engine.get_template('modo_render_commands_win.txt') if pathaliases: for key in pathaliases: '{} "{}"'.format(key, os.path.normpath(pathaliases[key])) for scene in scenes: scenes[scene]['path'] = format_filename(scenes[scene]['path'], 'win32') return template.render({'pathaliases': pathaliases, 'scenes': scenes})
def generate(filename, serial_no, settings, data): path = Path(__file__).parent / 'views' searchpath = [str(path)] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension()]) engine.global_vars.update({'format_value': format_value}) template = engine.get_template('template.html') with open(filename, 'w') as f: f.write( template.render({ 'data': data, 'serial_no': serial_no, 'noun': settings['dut'] }))
def to_autopkg(self, outfile): searchpath = [ os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') ] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension()]) template = engine.get_template('redist-packages.autopkg') autopkg = template.render({'package': self}) with open(outfile, 'w') as f: f.write(autopkg) return autopkg
class FileLoaderTestCase(unittest.TestCase): """ Test the ``FileLoader``. """ def setUp(self): import os.path from wheezy.template.loader import FileLoader self.tmpldir = os.path.dirname(__file__) self.loader = FileLoader(directories=[self.tmpldir]) @patch('os.walk') def test_get_template(self, mock_walk): mock_walk.return_value = [ (self.tmpldir + '/', ['.ignore', 'shared'], ['.ignore', 'tmpl1.html']), (self.tmpldir + '/shared', ['.ignore', 'snippet'], ['master.html', '.ignore']), (self.tmpldir + '/shared/snippet', ['.ignore'], ['.ignore', 'script.html']) ] assert ('shared/master.html', 'shared/snippet/script.html', 'tmpl1.html') == self.loader.list_names() def test_load_existing(self): """ Tests load. """ assert '' == self.loader.load('__init__.py') def test_load_not_found(self): """ Tests load if the name is not found. """ assert not self.loader.load('tmpl-x.html') def test_load_not_a_file(self): """ Tests load if the name is not a file. """ assert not self.loader.load('..')
def main(args=None): if not json: # pragma: nocover print('error: json module is not available') return 1 args = parse_args(args or sys.argv[1:]) if not args: return 2 ts = args.token_start extensions = [CoreExtension(ts), CodeExtension(ts)] extensions.extend(args.extensions) engine = Engine(FileLoader(args.searchpath), extensions) engine.global_vars.update({'h': escape}) t = engine.get_template(args.template) sys.stdout.write(t.render(load_context(args.context))) return 0
def build_modo_batch(commands=[], headless=""): import ntpath searchpath = [TEMPLATES] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension()]) template = engine.get_template('modo_batch.bat') win_commands = [] for command in commands: win_commands.append(ntpath.normpath(format_filename(command, 'win32'))) headless = ntpath.normpath( r"C:\Program Files\Luxology\modo\11.0v1\modo_cl.exe") return template.render({ 'modo_cl': ntpath.normpath(headless), 'commands': win_commands })
def __init__(self, searchpath): Formatter.__init__(self) self._symbol_formatters = { FunctionSymbol: self._format_function, FunctionMacroSymbol: self._format_function_macro, CallbackSymbol: self._format_callback, ConstantSymbol: self._format_constant, ExportedVariableSymbol: self._format_constant, AliasSymbol: self._format_alias, StructSymbol: self._format_struct, EnumSymbol: self._format_enum, ParameterSymbol: self._format_parameter_symbol, ReturnItemSymbol: self._format_return_item_symbol, FieldSymbol: self._format_field_symbol, SignalSymbol: self._format_signal_symbol, VFunctionSymbol: self._format_vfunction_symbol, PropertySymbol: self._format_property_symbol, ClassSymbol: self._format_class_symbol, InterfaceSymbol: self._format_interface_symbol, } self._ordering = [InterfaceSymbol, ClassSymbol, FunctionSymbol, FunctionMacroSymbol, SignalSymbol, PropertySymbol, StructSymbol, VFunctionSymbol, EnumSymbol, ConstantSymbol, ExportedVariableSymbol, AliasSymbol, CallbackSymbol] if HtmlFormatter.theme_path: self.__load_theme_templates(searchpath, HtmlFormatter.theme_path) if HtmlFormatter.extra_theme_path: self.__load_theme_templates(searchpath, HtmlFormatter.extra_theme_path) searchpath.append(os.path.join(HERE, "html_templates")) self.engine = Engine( loader=FileLoader(searchpath, encoding='UTF-8'), extensions=[CoreExtension(), CodeExtension()] ) self.all_scripts = set() self.all_stylesheets = set() self._docstring_formatter = GtkDocStringFormatter()
def parse_toplevel_config(self, config): """Parse @config to setup @self state.""" if not Formatter.initialized: html_theme = config.get('html_theme', 'default') if html_theme != 'default': uri = urllib.parse.urlparse(html_theme) if not uri.scheme: html_theme = config.get_path('html_theme') debug("Using theme located at %s" % html_theme) elif uri.scheme.startswith('http'): html_theme = self.__download_theme(uri) if html_theme == 'default': default_theme = os.path.join(HERE, os.pardir, 'hotdoc_bootstrap_theme', 'dist') html_theme = os.path.abspath(default_theme) debug("Using default theme") theme_meta_path = os.path.join(html_theme, 'theme.json') if os.path.exists(theme_meta_path): with open(theme_meta_path, 'r') as _: Formatter.theme_meta = json.loads(_.read()) searchpath = [] self.__load_theme_templates(searchpath, HERE) Formatter.theme_path = html_theme if html_theme: self.__load_theme_templates(searchpath, html_theme) Formatter.extra_theme_path = config.get_path('html_extra_theme') if Formatter.extra_theme_path: self.__load_theme_templates(searchpath, Formatter.extra_theme_path) Formatter.engine = Engine( loader=FileLoader(searchpath, encoding='UTF-8'), extensions=[CoreExtension(), CodeExtension()]) Formatter.engine.global_vars.update({'e': html.escape}) Formatter.initialized = True
def parse_config(self, config): """Banana banana """ self.add_anchors = bool(config.get("html_add_anchors")) self.number_headings = bool(config.get("html_number_headings")) if self.theme_path: self.__load_theme_templates(self.searchpath, self.theme_path) if self.extra_theme_path: self.__load_theme_templates(self.searchpath, self.extra_theme_path) self.searchpath.append(os.path.join(HERE, "templates")) self.engine = Engine(loader=FileLoader(self.searchpath, encoding='UTF-8'), extensions=[CoreExtension(), CodeExtension()]) self.engine.global_vars.update({'e': html.escape}) self._docstring_formatter.parse_config(config)
def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super().__init__(params) self.template_context_processors = options.pop('context_processors', []) if 'loader' not in options: options['loader'] = FileLoader(self.template_dirs) options.setdefault('autoescape', True) options.setdefault('auto_reload', settings.DEBUG) self.engine = Engine(loader=options['loader'], extensions=[CoreExtension()]) self.engine.global_vars.update({ 'e': escape, 'escape': escape, 'static': static })
def generate_source(options, version, enums, functions_by_category, passthru, extensions): template_pattern = re.compile("(.*).template") template_namespace = {'passthru' : passthru, 'functions' : functions_by_category, 'enums' : enums, 'options' : options, 'version' : version, 'extensions': extensions} if not os.path.isdir(options.template_dir): print ('%s is not a directory' % options.template_dir) exit(1) if os.path.exists(options.outdir) and not os.path.isdir(options.outdir): print ('%s is not a directory' % options.outdir) exit(1) if not os.path.exists(options.outdir): os.mkdir(options.outdir) engine = Engine(loader=FileLoader([options.template_dir]), extensions=[CoreExtension()]) generatedFiles = 0 allFiles = 0; for template_path in glob('%s/*.template' % os.path.abspath(options.template_dir)): infile = os.path.basename(template_path) outfile = '%s/%s' % (options.outdir, template_pattern.match(infile).group(1)) template = engine.get_template(infile) allFiles += 1 with open(outfile, 'w') as out: out.write(template.render(template_namespace)) print("Successfully generated %s" % outfile) generatedFiles += 1; print("Generated %d of %d files" % (generatedFiles, allFiles))
finally: server.stop() template = """\ @require(name) Hello, @name""" engine_dict = Engine(loader=DictLoader({'x': template}), extensions=[CoreExtension()]) template_w = engine_dict.get_template('x') searchpath = ['./static/templates-wheezy'] #searchpath = ['./views'] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension(), CodeExtension()]) templateChild = engine.get_template('child.html') template_famille = engine.get_template('famille.html') @route("/") def working(): return "Site en maintenance" @route('/img/<filename>') def send_static(filename): return static_file(filename, root='static/img')
from wfw.library import library from wfw.constants import * from wheezy.template.engine import Engine from wheezy.template.ext.core import CoreExtension from wheezy.template.loader import FileLoader searchpath = [WFW_APPPATH + "views/"] engine = Engine(loader=FileLoader(searchpath), extensions=[CoreExtension()]) class load(library): def view(self, name, data={}): template = engine.get_template(name + ".tpl") return str(template.render(data)) def model(self, name): pack = WFW_APPFOLDER + ".models." + name package = __import__(pack, fromlist=[name]) cl = getattr(package, name) self._set(name, cl())
if 'code' not in extends_tokens: extends_tokens.append('code') class AutoRequireExtension: def __init__(self, *names): self.names = names @property def postprocessors(self): yield self.add_require def add_require(self, tokens): tokens.insert(0, (0, 'require', f"require({','.join(self.names)})")) engine = Engine( loader=FileLoader(['.']), extensions=[ CoreExtension(token_start='\\$'), CodeExtension(token_start='\\$'), AutoRequireExtension('config', 'urls', 'db', 'endpoint', 'values'), ]) with catch_warnings(record=True): engine = autoreload(engine) engine.global_vars.update( {'_r': engine.render, 'warn': warn, 'json': json})
# update again, see if everything exported file_df = export_info(file_df) need_update = file_df.query('export_date != export_date or export_date < mt') if len(need_update) != 0: print("some files failed to update: %s!" % (",".join(need_update['title']))) # export_to is relative to this script. should be relative to index.html # remove '../' file_df['uri'] = [re.sub('^\.\./', '', x) for x in file_df['export_to']] # index template from wheezy.template.engine import Engine from wheezy.template.ext.core import CoreExtension from wheezy.template.loader import FileLoader engine = Engine(loader=FileLoader(['../src/']), extensions=[CoreExtension()]) template = engine.get_template('index.tmp') # write it out index_str = template.render({'file_df': file_df, 'title': 'WF log'}) with open('../index.html', 'w') as indexf: indexf.write(index_str) def gopher_path(f): txt = re.sub('.org$', '.txt', f) return re.sub('^', '../gopher/', txt) gopher_df = file_df[['f', 'title', 'date']].copy() gopher_df['ln_to'] = [gopher_path(f) for f in gopher_df['f']] gopher_df['need_ln'] = [not os.path.exists(f) for f in gopher_df['ln_to']]
metavar="DIR", default=".") (options, args) = parser.parse_args() namespace = { 'type_dic': type_dic, 'int_type_dic': int_type_dic, 'format_dic': format_dic, 'format_map': format_map, 'linear_format_map': linear_format_map, 'int_format_map': int_format_map, 'reverse_map': reverse_map } generated_warning = '/* WARNING: This file was automatically generated */\n/* Do not edit. */\n' with open('%s/format_map.%s' % (options.output_dir, options.source_ext), 'w') as source_file: source_file.write(generated_warning) engine = Engine(loader=FileLoader([script_dir]), extensions=[CoreExtension()]) template = engine.get_template( os.path.basename('%s/format_map_template.cc' % script_dir)) source_file.write(template.render(namespace)) with open('%s/format_map.%s' % (options.output_dir, options.header_ext), 'w') as header_file: header_file.write(generated_warning) header_file.write(header_content)
import json import os.path from wheezy.template.engine import Engine from wheezy.template.ext.core import CoreExtension from wheezy.template.loader import FileLoader engine = Engine(loader=FileLoader(["."]), extensions=[CoreExtension(line_join="")]) config = json.load(open("generate.json")) for t in config["targets"]: template = engine.get_template( os.path.join(t["base"], "Dockerfile.template")) defaults = t.get("defaults", {}) for variant in t["variants"]: context = dict(defaults, **variant["context"]) content = template.render(context) out = os.path.join(t["base"], variant["out"], "Dockerfile") with open(out, "w", newline="\r\n") as f: f.write(content)
url(r'^nodes', nodes, name='nodes'), url(r'^id', get_id, name='id'), url(r'^data', data, name='data'), url(r'^zigbee', datatoZigBee, name='zigbee'), url('static/{path:any}', file_handler(root='static/'), name='static') ] # Configuracion del servidor HTTP options = {} # Template Engine searchpath = ['templates'] engine = Engine( loader=FileLoader(searchpath), extensions=[ CoreExtension(), WidgetExtension(), ]) engine.global_vars.update({ 'h': html_escape }) options.update({ 'render_template': WheezyTemplate(engine) }) # Clase principal para la gestion de Websockets class UMAApplication(WebSocketApplication): global dictionary