def test_t(self): # print(pystache.render('Hi {{person}}!', {'person': 'Mom'})) # todo # hello = SayHello() # Hello, {{to}}! # print(hello) # renderer = pystache.Renderer() # print(renderer.render(hello)) # todo print(pystache.render('Hi {{person}}!', {'person': 'seveniruby'})) # Hi seveniruby! # todo print("==" * 30) parsed = pystache.parse(u"Hey {{#who}}{{.}}!{{/who}}") # 模版与变量 # print(parsed) renderer = pystache.Renderer() print(renderer.render(parsed, {'who': 'Pops'})) print(renderer.render(parsed, {'who': 'you'})) # 另一套体系 context = {'author': 'Chris Wanstrath', 'maintainer': 'Chris Jerdonek'} print( pystache.render("Author: {{author}}\nMaintainer: {{maintainer}}", context)) print( renderer.render( pystache.parse(u"test: {{#author}}{{.}}!{{/author}}"), {'author': 'maintainer'}))
def _validate_mustache_template(mustache_path): with open(mustache_path, encoding='utf-8') as f: mustache_template = f.read() try: pystache.parse(mustache_template) except ParsingError as pe: sys.exit("\tERROR\n\nParsing error: {}".format(str(pe)))
def _render(self, articles): template_string = '' with open(self.template['content'], 'r') as f: template_string = f.read().decode('utf-8') content_parsed = pystache.parse(template_string) with open(self.template['layout'], 'r') as f: template_string = f.read().decode('utf-8') layout_parsed = pystache.parse(template_string) params = [] for article in articles: dt = datetime.datetime.fromtimestamp(article['issued']) params.append({ 'href': article['filename'] + '.html', 'date': dt.strftime('%b %d, %Y'), 'title': article['title'], }) contents = self.renderer.render(content_parsed, {'articles': params}) dt = datetime.datetime.now() param = { 'content': contents, 'date': dt.strftime('%b %d, %Y'), 'date_iso': dt.isoformat(), 'author': articles[0]['author'], 'url': self.html_filename, } dest_path = os.path.join(self.output_path, self.html_filename) with open(dest_path, 'w') as f: f.write(self.renderer.render(layout_parsed, param).encode('utf-8'))
def __init__(self, template_file, dest_file_template_str, overwrite=True): """Ctor. @param template_file: Filename of the mustache template. @param dest_file_template_str: Destination file name. This is a mustache template, so each resource can write to a unique file. @param overwrite: If True, destination file is ovewritten if it exists. """ template_str = unicode(open(template_file, "r").read()) self.template = pystache.parse(template_str) dest_file_template_str = unicode(dest_file_template_str) self.dest_file_template = pystache.parse(dest_file_template_str) self.overwrite = overwrite
def render(values): renderer = pystache.Renderer() with codecs.open('template.mustache', 'r', 'utf-8') as templateFile: template = templateFile.read() parsed = pystache.parse(template) return renderer.render(parsed, values)
def begin_generation(rule): context.class_map = {} for output in rule['output']: with codecs.open(bindings_path + output['template'], 'r', "utf-8") as data_file: output['parsed-template'] = pystache.parse(data_file.read()) output['extraction'] = Extraction()
def gen_colours(parts, output_dir): """ Generates a colours.py from library data """ print('generate ldraw.library.colours...') colours_mustache = get_resource( os.path.join('templates', 'colours.mustache')) colours_template_file = codecs.open(colours_mustache, 'r', encoding='utf-8') colours_template = pystache.parse(colours_template_file.read()) context = { 'colours': [get_c_dict(c) for c in parts.colours_by_name.values()] } context['colours'].sort(key=lambda r: r['code']) colours_str = pystache.render(colours_template, context=context) library_path = os.path.join(output_dir, 'library') colours_py = os.path.join(library_path, 'colours.py') with codecs.open(colours_py, 'w', encoding='utf-8') as generated_file: generated_file.write(colours_str)
def mustache_template(self, namespace, data): """ Takes a namespace and finds it's file. Takes that file and parses it's template. Then takes that template, loads the partials for it, and renderers the template, given the data and the partials. """ partials_path = config.build_paths['partials_path'] + "/" paths = namespace.split('.') file_path = '/'.join(paths) + '.mustache' partials = dict() if self.application.debug == True: with open(config.build_paths['mustache_path'] + '/' + file_path) as f: read_data = f.read() read_data = unicode(read_data) for (dirpath, dirname, filenames) in os.walk(partials_path): dirpath += '/' if not dirpath.endswith('/') else '' new_namespace = dirpath.replace(partials_path, '') new_namespace = new_namespace.replace('/', '.') for filename in filenames: if filename.endswith('.mustache'): with open(dirpath + filename) as f: read_file = f.read() filename = filename.replace(".mustache", "") partials[new_namespace + filename] = read_file parsed_template = pystache.parse(read_data) renderer = pystache.Renderer(partials=partials) return renderer.render(parsed_template, data) else: return 'no bueno'
def parse_templates(self, templates): for template in templates: print "Parse template: %s" % os.path.join(self.template_dir, template) with codecs.open(os.path.join(self.template_dir, template), 'r', 'utf-8') as content_file: content = content_file.read() self.templates[template.strip('.mustache')] = pystache.parse(content)
def parse_template(template_text): if six.PY2: # pystache does a typecheck for unicode in python 2.x but rewrites its sources to deal # unicode via str in python 3.x. template_text = unicode(template_text) template = pystache.parse(template_text) return template
def generate_xmls(json_filenames): xml_template_str = unicode(open('tool-template.xml').read()) xml_template = pystache.parse(xml_template_str) for tool_path in json_filenames: desc = json.load(open(tool_path)) desc['collectionName'] = desc['collectionName'].capitalize() print pystache.render(xml_template, desc)
class PystacheBench: template = pystache.parse(''' {{ #steps }} .. only:: not (html or dirhtml or singlehtml) Step 0: {{ title }} {{ heading }} {{body}} .. only:: html or dirhtml or singlehtml .. raw:: html <div class="sequence-block"> <div class="bullet-block"> <div class="sequence-step">0</div></div> {{title}} {{heading}} {{body}} .. raw:: html </div> {{/steps}} ''') @classmethod def bench(cls): pystache.render(cls.template, DATA)
def parse_mustache_template(self, origin, source): if origin not in self._parsed or settings.DEBUG: # no cache in DEBUG mode try: self._parsed[origin] = pystache.parse(smart_unicode(source)) except pystache.parser.ParsingError, e: # better error raise pystache.parser.ParsingError("Mustache couldn't parse {0}, reason : '{1}'.".format(origin, e))
def remove_components(self, template, tags): new_components = [] tags = set(tags) parsed = pystache.parse(safe_decode(template)) last_removed = False for i, el in enumerate(parsed._parse_tree): if hasattr(el, 'parsed'): keys = [e.key for e in el.parsed._parse_tree if hasattr(e, 'key') and e.key not in tags] if keys: new_components.append(self.build_first_of_template(keys)) last_removed = False else: last_removed = True elif hasattr(el, 'key'): if el.key not in tags: new_components.append('{{{{{{{key}}}}}}}'.format(key=el.key)) last_removed = False else: last_removed = True elif not last_removed: new_components.append(el) else: last_removed = False return ''.join(new_components).strip()
def __init__(self, template_text, **template_data): # pystache does a typecheck for unicode in python 2.x but rewrites its sources to deal unicode # via str in python 3.x. if Compatibility.PY2: template_text = unicode(template_text) self._template = pystache.parse(template_text) self.template_data = template_data
def remove_components(self, template, tags): new_components = [] tags = set(tags) parsed = pystache.parse(safe_decode(template)) last_removed = False for i, el in enumerate(parsed._parse_tree): if hasattr(el, 'parsed'): keys = [ e.key for e in el.parsed._parse_tree if hasattr(e, 'key') and e.key not in tags ] if keys: new_components.append(self.build_first_of_template(keys)) last_removed = False else: last_removed = True elif hasattr(el, 'key'): if el.key not in tags: new_components.append( '{{{{{{{key}}}}}}}'.format(key=el.key)) last_removed = False else: last_removed = True elif not last_removed: new_components.append(el) else: last_removed = False return ''.join(new_components).strip()
def subscribe(args): consumer = KafkaConsumer(args.kafka_topic, group_id=args.kafka_group_id, metadata_broker_list=args.kafka_server.split(',')) renderer = pystache.Renderer() logging.info("rsync_cmd: [{0}]".format(" ".join(args.rsync_cmd))) templates = [ pystache.parse(unicode(c,"UTF-8")) for c in args.rsync_cmd ] for message in consumer: o = json.loads(message.value) if not "maskname" in o: continue if o["maskname"] in ["IN_IGNORED","IN_DELETE"]: continue if 'dir' in o and o['dir']: continue cmd = [ renderer.render(t, {'o': o,'args':args}) for t in templates ] target = cmd[-1] # ensure the parent folder exists, having a hard time # otherwise getting rsync to do this folder = os.path.dirname(cmd[-1]) if not os.path.exists(folder): os.makedirs(folder) cmd.insert(0,"rsync") logging.info("executing: "+" ".join(cmd)) try: subprocess.check_call(cmd) except subprocess.CalledProcessError, e: logging.info("failed to execute: "+" ".join(cmd)) if e.output: logging.info(e.output)
def export(self, template_file_name, output_file_name, sort="public", data=None, limit=0): """Export ranking to a file. Args: template_file_name (str): where is the template (moustache template) output_file_name (str): where create the file with the ranking sort (str): field to sort the users """ exportedData = {} exportedUsers = self.__exportUsers(sort, limit) exportedData["users"] = exportedUsers exportedData["extraData"] = data with open(template_file_name) as template_file: template_raw = template_file.read() template = parse(template_raw) renderer = Renderer() output = renderer.render(template, exportedData) with open(output_file_name, "w") as text_file: text_file.write(output)
def render(self, state): renderer = pystache.renderer.Renderer() with Server.pagefile.open("r") as f: template = f.read() page = pystache.parse(template) result = renderer.render(page, state) return result
def __init__(self, template_dir, template_file): """Create a new PystacheMessageBuilder that uses the specified template file. :param template_dir: The directory to load template files from :param template_file: The template file to populate with values. """ self._renderer = Renderer(search_dirs=template_dir) raw_template = self._renderer.load_template(template_file) self._parsed_template = pystache.parse(raw_template)
def create_mustache_category(filename): """ Creates a Mustache parser object with the given file :param filename: filename to parse :return: Parser object from Mustache """ return pystache.parse(read_fully(filename))
def render(cls, path, dict): # 模版路径;发送请求路径 render = pystache.Renderer(escape=lambda u: u) # 完全禁用转义功能 print(os.path.abspath(os.getcwd())) # todo 当前目录 with open(path) as f: # 打开模版 content = f.read() # 读取模版 parsed = pystache.parse(content) # result = render.render(parsed, dict) return result
def render(cls, path, dict): render = pystache.Renderer(escape=lambda u: u) # 完全禁用转义符 print(os.path.abspath(os.getcwd())) with open(path) as f: content = f.read() # 读取模板内容 parsed = pystache.parse(content) # 将模板内容转换成为模板对象 result = render.render(parsed, dict) # 模板对象还有字典内容整合起来 return result
def build(self, profile): """ Build static website """ Console.info("Executing Konstrukteur...") Console.indent() self.__templatePath = os.path.join("source", "template") self.__contentPath = os.path.join("source", "content") self.__sourcePath = os.path.join("source") self.__profile = profile self.__fileManager = FileManager.FileManager(profile) if not os.path.exists(self.__templatePath): raise RuntimeError("Path to templates not found : %s" % self.__templatePath) if not os.path.exists(self.__contentPath): raise RuntimeError("Path to content not found : %s" % self.__contentPath) if self.theme: theme = session.getProjectByName(self.theme) if not theme: raise RuntimeError("Theme '%s' not found" % self.theme) self.__postUrl = pystache.parse(self.posturl) self.__pageUrl = pystache.parse(self.pageurl) self.__feedUrl = pystache.parse(self.feedurl) self.__parseTemplate() self.__build() if self.regenerate: fileChangeEventHandler = konstrukteur.FileWatcher.FileChangeEventHandler() observer = Observer() observer.schedule(fileChangeEventHandler, self.__sourcePath, recursive=True) observer.start() try: Console.info("Waiting for file changes (abort with CTRL-C)") while True: time.sleep(1) if fileChangeEventHandler.dirty: fileChangeEventHandler.dirty = False self.__build() except KeyboardInterrupt: observer.stop() observer.join() Console.outdent()
def render(cls, path, dict): render = pystache.Renderer(escape=lambda u: u) print(os.path.abspath(os.getcwd())) with open(path) as f: content = f.read() parsed = pystache.parse(content) result = render.render(parsed, dict) return result
def get_file_content(self): with open( join(dirname(__file__), 'templates', 'conversions.template.js'), 'r') as template_file: return render(parse(unicode(template_file.read())), { 'edges': self.edges, 'quantities': self.quantities }) return ''
def parse_mustache_template(self, origin, source): if origin not in self._parsed or settings.DEBUG: # no cache in DEBUG mode try: self._parsed[origin] = pystache.parse(smart_unicode(source)) except pystache.parser.ParsingError, e: # better error raise pystache.parser.ParsingError( "Mustache couldn't parse {0}, reason : '{1}'.".format( origin, e))
def render(cls, path, dict): try: render = pystache.Renderer(escape=lambda u: u) with open(path) as f: content = f.read() parsed = pystache.parse(content) result = render.render(parsed, dict) return result except Exception as e: raise e
def render(cls, path, dict): render = pystache.Renderer(escape=lambda u: u) with open(path) as f: content = f.read() parsed = pystache.parse(content) print(parsed) print("测试打印") result = render.render(parsed, dict) print(result) return result
def __init__(self): client = pymongo.MongoClient() self.auth_db = flowboard_auth.AuthDatabase(client) self.auth_service = flowboard_auth.AuthService(self.auth_db) self.posts_db = flowboard_posts.PostDatabase(client) FlowBoard.instance = self self.secret = "6LekGR4TAAAAADn4OR-Gr8pYqdpIJiv79re8fy24" self.index_parsed = pystache.parse(''.join(open('index.html').readlines())) self.renderer = pystache.Renderer() self.recent_posts_html = self.most_recent_posts_html(10) self.notify_update()
def main(config: dict, *args, **kwargs) -> Iterator[Item]: path = Path(config['path']) subprovider = path.name logger.info('Reading CSV file %s', path) renderer = pystache.Renderer(escape=lambda u: u) date_source_tmpl = pystache.parse(config['date_source']) text_source_tmpl = pystache.parse(config['text_source']) with path.open() as f: reader = csv.DictReader(f) for row in reader: text = renderer.render(text_source_tmpl, row) datetime_ = datetime.datetime.strptime( renderer.render(date_source_tmpl, row), config['date_format']) yield Item.normalized( datetime_=datetime_, text=text, provider=provider, subprovider=subprovider, all_day=True, )
def render_string_with_secrets(string, secrets) -> str: if not secrets: return string secret_dict = _convert_to_dict(secrets) parsed = pystache.parse(string, delimiters=("<%", "%>")) for token in parsed._parse_tree: #pylint: disable=protected-access if isinstance(token, pystache.parser._EscapeNode): #pylint: disable=protected-access token.key = re.sub( r"\[(\d+)\]", r".\1", token.key) # make format such as $secrets.data[0] works return pystache.Renderer().render(parsed, {"$secrets": secret_dict})
def _render_user_command(user_command, secrets) -> str: if not secrets: return user_command LOGGER.info("not rendered user command is %s", user_command) secret_dict = _convert_to_dict(secrets) parsed = pystache.parse(user_command, delimiters=("<%", "%>")) for token in parsed._parse_tree: #pylint: disable=protected-access if isinstance(token, pystache.parser._EscapeNode): #pylint: disable=protected-access token.key = re.sub( r"\[(\d+)\]", r".\1", token.key) # make format such as $secrets.data[0] works return pystache.Renderer().render(parsed, {"$secrets": secret_dict})
def render(self, template_path, output_path, variables={}): with open (self.template_root + template_path, "r") as myfile: data=myfile.read() parsed = pystache.parse(u"%(data)s" % locals()) renderer = pystache.Renderer() output = renderer.render(parsed, variables) with open (os.getcwd() + "/temp/" + output_path, "w") as myfile: myfile.write(output) return os.getcwd() + "/temp/" + output_path
def __init__(self, template: str, project: str, component: str): template_data = io.BytesIO() copy_from_url(template, template_data) template_data.seek(0) self._template = pystache.parse(template_data.read()) self._data = { "project": project, "component": component, "info": [], "table_header": None, "files": [] }
def get_template_keys(self, event_type, template): tmpl_keys = [] tmpl = self.get_file(event_type, template) fp = open(tmpl, "r") fp_buf = fp.read() parsed = pystache.parse(fp_buf) for k in parsed._parse_tree: if isinstance( k, (pystache.parser._SectionNode, pystache.parser._LiteralNode)): tmpl_keys.append(k.key) fp.close() return tmpl_keys
def main(config_path): with open(config_path) as simple_config_file: simple_config=json.load(simple_config_file) # These are not something the user will put into their simple config, # so we need to get it from the environment (it will have been set by the start_services_in_container.sh script) simple_config['sensu_server_ip_address'] = os.environ['SENSU_SERVER_IP_ADDRESS'] simple_config['queue_host'] = os.environ['SENSU_SERVER_IP_ADDRESS'] simple_config['fleet_name'] = os.environ['FLEET_NAME'] config_path = os.path.dirname(__file__) with open(config_path +'/pancancer_config.mustache') as mustache_template_file: mustache_template=mustache_template_file.read() renderer=pystache.Renderer() parsed=pystache.parse(mustache_template) rendered_str=renderer.render(parsed,(simple_config)) data=json.loads(rendered_str) # The master config file should be written to ~/.pancancer/pancancer_config.json with open(config_path + '/pancancer_config.json','w') as master_config_file: master_config_file.write(str(json.dumps(data,sort_keys=True, indent=4) )) # Youxia config should go to ~/.youxia/config with open(config_path + '/youxia_config','w') as youxia_file: youxia_settings=data['youxia'] youxia_str=processYouxiaSettings(youxia_settings) youxia_file.write(youxia_str) # params.json should go to ~/params.json with open(config_path + '/params.json','w') as params_json_file: params_settings=data['params'] params_str=processParams(params_settings) params_json_file.write(params_str) # masterConfig should go to ~/arch3/config/masterConfig.ini with open(config_path + '/masterConfig.ini','w') as consonance_file: consonance_settings=data['consonance'] consonance_str=processConsonanceSettings(consonance_settings) consonance_file.write(consonance_str) #create the server tags, if necessary. The user can change this file later, and we won't touch it (since it already exists). server_tags_path = os.path.expanduser('~/arch3/server-tags.json') if not os.path.exists(server_tags_path): with open(server_tags_path,'w') as server_tags_file: server_tags={'KEEP':os.environ['FLEET_NAME']} server_tags_file.write(str(json.dumps(server_tags,sort_keys=True, indent=4) )) shutil.copy2(config_path + '/youxia_config','/home/ubuntu/.youxia/config') shutil.copy2(config_path + '/masterConfig.ini','/home/ubuntu/arch3/config/masterConfig.ini') shutil.copy2(config_path + '/params.json','/home/ubuntu/params.json')
def format_address(self, components, country, language, minimal_only=True, tag_components=True, replace_aliases=True): if minimal_only and not self.minimal_components(components): return None template = self.get_template(country, language=language) if not template: return None if not template or 'address_template' not in template: return None template_text = template['address_template'] template_text = self.revised_template(template_text, components, country, language=language) if template_text is None: return None if tag_components: template_text = self.tag_template_separators(template_text) if template_text in self.parsed_cache: template = self.parsed_cache[template_text] else: template = pystache.parse(template_text) self.parsed_cache[template_text] = template if replace_aliases: self.aliases.replace(components) if tag_components: components = { k: self.tagged_tokens(v, k) for k, v in six.iteritems(components) } text = self.render_template(template, components, tagged=tag_components) text = self.remove_repeat_template_separators(text) return text
def template_tags(self): parsed_template = pystache.parse(self.template) keys = [] parse_tree = parsed_template._parse_tree keyed_classes = (pystache.parser._EscapeNode, pystache.parser._LiteralNode, pystache.parser._InvertedNode, pystache.parser._SectionNode) for token in parse_tree: if isinstance(token, keyed_classes): keys.append(token.key) # return list of unique items # (json does not like sets) return list(set(keys))
def __getTemplate(template_file_name): """Get temaplte to save the ranking. :param template_file_name: path to the template. :type template_file_name: str. :return: template for the file. :rtype: pystache's template. """ with open(template_file_name) as template_file: template_raw = template_file.read() template = pystache.parse(template_raw) return template
def __init__(self,argv,cols_): self.db = DEFDB self.noddl = False self.dbdir = None self.tables = {} self.tableList = [] optlist, _ = getopt.getopt(argv, "", LONGOPTIONS) for opt,arg in optlist: if opt == "--dbconf": self.dbconfFile = arg elif opt == "--dbdir": self.dbdir = arg elif opt == "--noddl": self.noddl = True if self.dbconfFile is None: raise Exception( "Missing required --dbconf file.") if PatJSON.match( self.dbconfFile ) is None: self.dbconfFile += ".json" if not os.path.isfile(self.dbconfFile): raise Exception( "Missing DBConf file. %s" % (self.dbconfFile) ) with open (self.dbconfFile, "r") as f: self.dbconf = json.load(f) if self.dbdir is None: if "dbdir" not in self.dbconf: raise Exception("Missing required --dbdir parameter or dbconf parameter.") self.dbdir = self.dbconf["dbdir"] if not os.path.isdir(self.dbdir): raise Exception("DBDir doesn't exists %s" % (self.dbdir) ) self.ddldbdir = self.dbdir + "/ddl" if not os.path.isdir(self.ddldbdir): raise Exception("DBDir/ddl doesn't exists %s" % (self.ddldbdir) ) self.dmldbdir = self.dbdir + "/dml" if not os.path.isdir(self.dmldbdir): raise Exception("DBDir/dml doesn't exists %s" % (self.dmldbdir) ) self.ddlrenderer = pystache.Renderer(search_dirs=[self.ddldbdir]) self.dmlrenderer = pystache.Renderer(search_dirs=[self.dmldbdir]) self.arraySubtables = self.dbconf["array_subtables"] if self.arraySubtables: if (not "array_template" in self.dbconf): self.dbconf["array_template"] = "arraytablename" self.arrayTemplate = self.ddlrenderer.load_template(self.dbconf["array_template"]) else: self.arrayTemplate = pystache.parse(self.dbconf["array_template"]) if self.arrayTemplate is None: raise Exception("Array table name template unable to load. %s" % (self.dbconf["array_template"])) for col in cols_.keys(): self.registerCol( col, cols_[col] ) self.genddl()
def template(x, cntx, master=False): # x = template name # cntx = stuff you want to pass # master = do not touch!!!! if x in templates: renderer = pystache.Renderer() o = renderer.render( templates[x], cntx ) if master: return o else: cntx['content'] = o return template("layout", cntx, True) else: templates[ x ] = pystache.parse( unicode(open('referencecat/gui/web/%s.html' % x).read() )) o = template( x, cntx, master ) if debug: del templates[x] return o
def create_changelog(current_version, previous_version, repo, milestone=None, token=os.environ.get('GITHUB_TOKEN', None), description=None, since=None, date=datetime.utcnow(), template=changelog_template, logger=EmptyLogger()): logger.debug('Creating changelog for %s from %s' % (current_version, repo)) description = description or 'The v%s release of %s' % (current_version, repo.split('/')[1]) issues = get_closed_issues(repo=repo, token=token, since=since, logger=logger) if milestone: milestone[ 'html_url'] = 'https://github.com/%s/issues?q=milestone%%3Av%s+is%%3Aall' % ( repo, current_version) data = { 'version': { 'from': str(previous_version) if previous_version > (0, 0, 0) else None, 'to': str(current_version), }, 'milestone': milestone, 'date': date.isoformat()[:10], 'repo': repo, 'description': description, 'issues': [i for i in issues if not i.get('pull_request', None)], 'pullrequests': [i for i in issues if i.get('pull_request', None)], } renderer = pystache.Renderer() parsed = pystache.parse(template) changelog = renderer.render(parsed, data) logger.info('Rendered changelog') return changelog
def _render(self, articles): template_string = '' with open(self.template['layout'], 'r') as f: template_string = f.read() parsed = pystache.parse(template_string) for article in articles: markdown_string = '' with open(article['path'], 'r') as f: f.readline() # remove header markdown_string = f.read() html = markdown2.markdown(markdown_string) dt = datetime.datetime.fromtimestamp(article['issued']) view_params = { 'title': article['title'], 'date': dt.strftime('%d %B %Y'), 'date_iso': dt.isoformat(), 'author': article['author'], 'url': article['filename'] + '.html', 'disqus_id': article['filename'], 'content': html, 'is_article': True, 'year': dt.strftime('%Y'), } if 'prev' in article: view_params['prev_article'] = { 'url': article['prev']['filename'] + '.html', 'title': article['prev']['title'] } if 'next' in article: view_params['next_article'] = { 'url': article['next']['filename'] + '.html', 'title': article['next']['title'] }, dest_path = os.path.join(self.output_path, article['filename'] + '.html') with open(dest_path, 'w') as f: f.write(self.renderer.render(parsed, view_params))
def format_address(self, components, country, language, minimal_only=True, tag_components=True, replace_aliases=True): if minimal_only and not self.minimal_components(components): return None template = self.get_template(country, language=language) if not template: return None if not template or 'address_template' not in template: return None template_text = template['address_template'] template_text = self.revised_template(template_text, components, country, language=language) if template_text is None: return None if tag_components: template_text = self.tag_template_separators(template_text) if template_text in self.parsed_cache: template = self.parsed_cache[template_text] else: template = pystache.parse(template_text) self.parsed_cache[template_text] = template if replace_aliases: self.aliases.replace(components) if tag_components: components = {k: self.tagged_tokens(v, k) for k, v in six.iteritems(components)} text = self.render_template(template, components, tagged=tag_components) text = self.remove_repeat_template_separators(text) return text
def export(self, template_file_name, output_file_name, sort): """Export ranking to a file Args: template_file_name (str): where is the template (moustache template) output_file_name (str): where create the file with the ranking sort (str): field to sort the users """ exportedData = {} dataUsers = self.getSortedUsers(sort) exportedUsers = [] position = 1 for u in dataUsers: userExported = u.export() userExported["position"] = position exportedUsers.append(userExported) if position < len(dataUsers): userExported["comma"] = True position+=1 exportedData["users"] = exportedUsers with open(template_file_name) as template_file: template_raw = template_file.read() template = pystache.parse(template_raw) renderer = pystache.Renderer() output = renderer.render(template, exportedData) with open(output_file_name, "w") as text_file: text_file.write(output)
def _render(self, articles): template_string = '' with open(self.template['layout'], 'r') as f: template_string = f.read() parsed = pystache.parse(template_string) contents = '' with open(self.template['content'], 'r') as f: contents = f.read() today = datetime.datetime.now() param = { 'content': contents, 'date': self.published_on.strftime('%d %B %Y'), 'date_iso': self.published_on.isoformat(), 'title': self.title, 'url': self.html_filename, 'year': today.strftime('%Y'), 'is_article': True, } dest_path = os.path.join(self.output_path, self.html_filename) with open(dest_path, 'w') as f: f.write(self.renderer.render(parsed, param))
def process(cls, graph, query_type): """ Process the query. :param DiGraph graph: the graph :param query_type: the type of query :type query_type: an element in keys() """ if query_type not in cls.keys(): raise DAGValueError('query_type must be among keys()') (klass, template_name) = cls._TABLE[query_type] result = klass.get(graph) template_path = os.path.normpath( os.path.join( os.path.dirname(__file__), '../data/html', template_name ) ) with open(template_path, 'r') as instream: template = instream.read() parsed = pystache.parse(template.decode()) return pystache.Renderer().render(parsed, result)
def __init__(self, pageName): """ Read data from filesystem """ self.pageName = pageName self.updateFileData() self.template = pystache.parse(unicode(self.fileData, 'utf-8'))
import pystache import os views = {} def render_view(view, data): data = pystache.render(views[view], data) return pystache.render(views['layout'], {'page': unicode(data)}) # Precompile templates for (dirpath, _, filenames) in os.walk('views'): for fname in filenames: path = dirpath + '/' + fname view = open(path, 'r').read() name = path[6:] if name.endswith('.stache'): name = name[0:len(name)-7] views[name] = pystache.parse(unicode(view))
def _parse_template(self, template): return pystache.parse(template.decode('utf-8'))
def collect_query_parameters(query): nodes = pystache.parse(query) keys = _collect_key_names(nodes) return keys
# Use the following for development so you do not hammer the GitHub API. #return {'name': name, 'html_url': 'http://google.com', 'homepage': 'http://example.com', 'description': 'Description!'} if not logged_in: time.sleep(2.0) # Take a nap so GitHub doesn't aggressively throttle us. repo = ghclient.repos.get(user='******', repo=name) return dict( name=repo.name, homepage=repo.homepage, html_url=repo.html_url, description=repo.description ) with codecs.open(index_in, 'r', 'utf-8') as f: template = pystache.parse(f.read()) with codecs.open(repos_in, 'r', 'utf-8') as f: repo_config = json.loads(f.read()) repos = repo_config['repos'] custom = repo_config['custom'] # Multimap of categories to their repos. categories = defaultdict(list) # Loop through declared repos, looking up their info on GitHub and adding to the specified categories. for repo in repos.keys(): repo_cats = repos[repo] repo_data = gh_repo(repo) if repo_cats is None: repo_cats = ['Other']
from getpass import getpass from time import sleep import smtplib from email.mime.text import MIMEText # change these each year when the chairs change CHAIRS = [ 'John Wenskovitch', 'Thomas Torsney-Weir', 'Timothy Luciani', 'Fumeng Yang', 'Tim Gerrits' ] email_tmpl = pystache.parse(open('./2018/regcode.txt.tmpl').read()) if len(CHAIRS) == 1: chair_names = CHAIRS[0] elif len(CHAIRS) == 2: chair_names = ' and '.join(CHAIRS) else: chair_names = ', '.join(CHAIRS[:-1]) + ', and ' + CHAIRS[-1] def read_csv(fname): with open(fname, 'r') as f: csvfile = csv.DictReader(f, delimiter=';') mem_csv = list(csvfile) return mem_csv def create_emails(svs):
def parse_template(template_text): template_text = six.text_type(template_text) template = pystache.parse(template_text) return template