def get_hbs(self, source, obj): compiler = Compiler() base_template = compiler.compile( u'<!DOCTYPE html><html lang="es">{{> head}}<body><div>{{> nav}}<div>{{> content}}</div></div>{{> footer}}</body></html>' ) head = compiler.compile( get_template("_head_organizations.html").render(obj)) footer = compiler.compile(get_template("_footer.html").render({})) content_template = compiler.compile(source) nav = compiler.compile(get_template("_navbar.html").render(obj)) def _proposal_card_renderer(proposal, *args, **kwargs): context = copy.copy(obj) request = context['view'].request context['proposal'] = proposal.get('this') return get_template( "popular_proposal/popular_proposal_card.html").render( context, request) everything = base_template( obj, partials={ "content": content_template, "head": head, "nav": nav, "footer": footer }, helpers={"proposal_card_renderer": _proposal_card_renderer}) return everything
def generate_page(data): compiler = Compiler() source = u"{{>header}}{{#list programs}}{{fileName}}{{lineCount}}{{/list}}" template = compiler.compile(source) def _list(this, options, items): result = [u"<ul>"] for thing in items: result.append(u"<li>") result.append(u'Source File:<a href="' + thing["fileName"] + '">' + thing["fileName"] + "</a>") result.append(u" - " + str(thing["lineCount"]) + " lines without comments or blank lines") result.append(u"</li>") result.append(u"</ul>") return result helpers = {"list": _list} # Add partials header = compiler.compile(u"<h1>Programs</h1>") partials = {"header": header} output = template(data, helpers=helpers, partials=partials) open("index.html", "wb").write(output)
def compile_template(template_dict, template_name): """Compile template.""" compiler = Compiler() partials = { name: compiler.compile(template) for name, template in template_dict.items() if name != template_name } compiled = compiler.compile(template_dict[template_name]) return compiled, partials
def render(source, context, helpers=None, partials=None, knownHelpers=None, knownHelpersOnly=False): compiler = Compiler() template = compiler.compile(source) # For real use, partials is a dict of compiled templates; but for testing # we compile just-in-time. if not partials: real_partials = None else: real_partials = dict((key, compiler.compile(value)) for key, value in list(partials.items())) return str_class(template(context, helpers=helpers, partials=real_partials))
def render_from_file(template_file, variables): """Render from template string with interpolated variables.""" compiler = Compiler() partials = { f.stem: compiler.compile(f.read_text()) for f in template_file.parent.glob("*.hbs") } source = template_file.read_text() template = compiler.compile(source, path=str(template_file.parent)) return template(variables, partials=partials)
def render_content(self, data, content): bars = Compiler() content = bars.compile(self._clean_content(content)) # need to render partials partials = {} for key, val in self._raw_partials.items(): partials[key] = bars.compile(self._clean_content(val)) return content(data, helpers=self._meta.helpers, partials=partials)
def render_content(self, data, content): bars = Compiler() content = bars.compile(self._clean_content(content)) # need to render partials partials = {} for key, val in self._raw_partials.items(): partials[key] = bars.compile(self._clean_content(val)) return content(data, helpers=self._meta.helpers, partials=partials)
def render(source, context, helpers=None, partials=None, knownHelpers=None, knownHelpersOnly=False): compiler = Compiler() template = compiler.compile(source) # For real use, partials is a dict of compiled templates; but for testing # we compile just-in-time. if not partials: real_partials = None else: real_partials = dict((key, compiler.compile(value)) for key, value in list(partials.items())) return str_class(template(context, helpers=helpers, partials=real_partials))
def blog_post(request, post_id): context = dict() r = requests.get('{0}/posts?api_key={1}&id={2}'.format(settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id)) if r.status_code == 200: post_response = r.json.get('response', {}) posts = post_response.get('posts', []) if posts: post = posts[0] f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z') post['formated_date'] = f_date.strftime('%B %d, %Y') if settings.DISQUS_INTEGRATION_ENABLED: post['disqus_enabled'] = True path_to_here = os.path.abspath(os.path.dirname(__file__)) f = open('{0}/static/templates/blog-post-{1}.html'.format(path_to_here, post['type']), 'r') f_data = f.read() f.close() compiler = Compiler() template = compiler.compile(unicode(f_data)) context['post_data'] = template(post) context['post_title'] = post.get('title', '') return render(request, 'blog-post.html', context)
def handlebars_dynamic_load(package, name): """ Dynamically compile a Handlebars template. NOTE: This will do nothing in production mode! """ if not App.is_dev_server: return None combined_name = "%s_%s" % (package, name) if combined_name in handlebars_partials: handlebars_partials[combined_name] logging.info("Dynamically loading %s-package/%s.handlebars." % (package, name)) file_name = "clienttemplates/%s-package/%s.handlebars" % (package, name) in_file = open(file_name, 'r') source = unicode(in_file.read()) # HACK: Pybars doesn't handle {{else}} for some reason source = source.replace("{{else}}", "{{^}}") matches = re.search('{{>[\s]*([\w\-_]+)[\s]*}}', source) if matches: for partial in matches.groups(): (partial_package, partial_name) = partial.split("_") handlebars_dynamic_load(partial_package, partial_name) compiler = Compiler() function = compiler.compile(source) handlebars_partials[combined_name] = function return function
def compileHandlebar(path, appName, paramPath=""): compiler = Compiler() source = "" templatePath = os.path.join(path, "templates/" + appName + "/src/config.py.hbs") with open(templatePath, 'r') as myfile: data=myfile.read() template = compiler.compile(data) if paramPath == "": paramPath = os.path.join(path, "parameters.json") with open(paramPath, 'r') as parameterJson: #check if template is filled with actual data content = json.load(parameterJson) for key,value in content.items(): for kkey, vvalue in value.items(): if "<" in vvalue or ">" in vvalue: raise ValueError ("The chosen param file does not contain all needed values.") appContent = content[appName] output = template(appContent) return output.lower()
def search_string(self): """" Returns the JSON string that LendingClub expects for it's search """ self.__normalize() # Get the template tmpl_source = str(open(self.tmpl_file).read()) # Process template compiler = Compiler() template = compiler.compile(tmpl_source) out = template(self) if not out: return False out = ''.join(out) # # Cleanup output and remove all extra space # # remove extra spaces out = re.sub('\n', '', out) out = re.sub('\s{3,}', ' ', out) # Remove hanging commas i.e: [1, 2,] out = re.sub(',\s*([}\\]])', '\\1', out) # Space between brackets i.e: ], [ out = re.sub('([{\\[}\\]])(,?)\s*([{\\[}\\]])', '\\1\\2\\3', out) # Cleanup spaces around [, {, }, ], : and , characters out = re.sub('\s*([{\\[\\]}:,])\s*', '\\1', out) return out
def _compile_template(swagger_template_file, template_params): compiler = Compiler() with codecs.open(swagger_template_file, 'r', 'utf-8') as f: template_file = f.read() template = compiler.compile(template_file) filled_template = template(template_params) return filled_template
def compileHandlebar(path, appName, paramPath=""): compiler = Compiler() source = "" templatePath = os.path.join(path, "templates/" + appName + "/src/config.py.hbs") with open(templatePath, 'r') as myfile: data = myfile.read() template = compiler.compile(data) if paramPath == "": paramPath = os.path.join(path, "parameters.json") with open(paramPath, 'r') as parameterJson: #check if template is filled with actual data content = json.load(parameterJson) for key, value in content.items(): for kkey, vvalue in value.items(): if "<" in vvalue or ">" in vvalue: raise ValueError( "The chosen param file does not contain all needed values." ) appContent = content[appName] output = template(appContent) return output.lower()
def create_and_save_doc(document_data, index_html, output_pdf): """ Creates a PDF invoice by filling an HTML template with a YML file. Parameters ---------- document_data : dict Data to use for filling the HTML template. index_html : str Absolute path to html template file. output_pdf : str Name of the output PDF file. Returns ------- Saves the output PDF to output/ directory """ pos_number = 1 document_data['totals'] = {'net': 0, 'gross': 0, 'tax': 0} for pos in document_data['positions']: if not 'tax_rate' in pos: pos['tax_rate'] = document_data['tax_rate'] pos['pos_number'] = pos_number pos['total_net_price'] = pos['net_price'] * pos['amount'] pos['total_tax'] = \ pos['total_net_price'] * (pos['tax_rate'] / float(100)) pos['total_gross_price'] = pos['total_net_price'] + pos['total_tax'] document_data['totals']['net'] += pos['total_net_price'] document_data['totals']['gross'] += pos['total_gross_price'] document_data['totals']['tax'] += pos['total_tax'] pos['amount'] = locale.format_string("%.2f", pos['amount']) pos['tax_rate'] = locale.format_string("%.2f", pos['tax_rate']) pos['net_price'] = locale.format_string("%.2f", pos['net_price']) pos['total_net_price'] = \ locale.format_string("%.2f", pos['total_net_price']) pos['text'] = pos['text'].replace('\n', '<br>') pos_number += 1 document_data['totals']['net'] = \ locale.format_string("%.2f", document_data['totals']['net']) document_data['totals']['gross'] = \ locale.format_string("%.2f", document_data['totals']['gross']) document_data['totals']['tax'] = \ locale.format_string("%.2f", document_data['totals']['tax']) with codecs.open(index_html, encoding="utf-8") as index_file: html_text = index_file.read() compiler = Compiler() template = compiler.compile(html_text) html_text = template(document_data) weasytemplate = HTML(string=html_text) weasytemplate.write_pdf(os.path.join('/app', 'output', output_pdf)) return
def handlebars_dynamic_load(package, name): """ Dynamically compile a Handlebars template. NOTE: This will do nothing in production mode! """ if not App.is_dev_server: return None combined_name = "%s_%s" % (package, name) if combined_name in handlebars_partials: handlebars_partials[combined_name] logging.info("Dynamically loading %s-package/%s.handlebars." % (package, name)) file_name = "clienttemplates/%s-package/%s.handlebars" % (package, name) in_file = open(file_name, 'r') source = unicode(in_file.read()) # HACK: Pybars doesn't handle {{else}} for some reason source = source.replace("{{else}}", "{{^}}") matches = re.search('{{>[\s]*([\w\-_]+)[\s]*}}', source) if matches: for partial in matches.groups(): (partial_package, partial_name) = partial.split("_") handlebars_dynamic_load(partial_package, partial_name) compiler = Compiler() function = compiler.compile(source) handlebars_partials[combined_name] = function return function
def test_smoke(self): compiler = Compiler() def _list(this, options, items): result = ['<ul>'] for thing in items: result.append('<li>') result.extend(options['fn'](thing)) result.append('</li>') result.append('</ul>') return result source = u"{{#list people}}{{firstName}} {{lastName}}{{/list}}" template = compiler.compile(source) context = { 'people': [{ 'firstName': "Yehuda", 'lastName': "Katz" }, { 'firstName': "Carl", 'lastName': "Lerche" }, { 'firstName': "Alan", 'lastName': "Johnson" }] } rendered = template(context, helpers={u'list': _list}) self.assertEqual( u"<ul><li>Yehuda Katz</li><li>Carl Lerche</li>"\ "<li>Alan Johnson</li></ul>", str_class(rendered))
def test_smoke(self): compiler = Compiler() def _list(this, options, items): result = ["<ul>"] for thing in items: result.append("<li>") result.extend(options["fn"](thing)) result.append("</li>") result.append("</ul>") return result source = u"{{#list people}}{{firstName}} {{lastName}}{{/list}}" template = compiler.compile(source) context = { "people": [ {"firstName": "Yehuda", "lastName": "Katz"}, {"firstName": "Carl", "lastName": "Lerche"}, {"firstName": "Alan", "lastName": "Johnson"}, ] } rendered = template(context, helpers={u"list": _list}) self.assertEqual( u"<ul><li>Yehuda Katz</li><li>Carl Lerche</li>" "<li>Alan Johnson</li></ul>", str_class(rendered) )
def blog_post(request, post_id): context = dict() r = requests.get('{0}/posts?api_key={1}&id={2}'.format( settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id)) if r.status_code == 200: post_response = r.json.get('response', {}) posts = post_response.get('posts', []) if posts: post = posts[0] f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z') post['formated_date'] = f_date.strftime('%B %d, %Y') path_to_here = os.path.abspath(os.path.dirname(__file__)) f = open( '{0}/static/templates/blog-post-{1}.html'.format( path_to_here, post['type']), 'r') f_data = f.read() f.close() compiler = Compiler() template = compiler.compile(unicode(f_data)) context['post_data'] = template(post) context['post_title'] = post['title'] return render(request, 'blog-post.html', context)
def blog_post(request, post_id): context = dict() r = requests.get('{0}/posts?api_key={1}&id={2}'.format( settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id)) if r.status_code == 200: post_response = r.json.get('response', {}) posts = post_response.get('posts', []) if posts: post = posts[0] f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z') post['formated_date'] = f_date.strftime('%B %d, %Y') if settings.DISQUS_INTEGRATION_ENABLED: post['disqus_enabled'] = True path = '{0}/static/templates/blog-post-{1}.html'.format( os.path.join(os.path.dirname(__file__), '..'), post['type']) with open(path, 'r') as f: f_data = f.read() compiler = Compiler() template = compiler.compile(unicode(f_data)) context['post_data'] = template(post) context['post_title'] = post.get('title', None) return render(request, 'blog-post.html', context)
def blog_post(request, post_id): context = dict() r = requests.get("{0}/posts?api_key={1}&id={2}".format(settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id)) if r.status_code == 200: post_response = r.json.get("response", {}) posts = post_response.get("posts", []) if posts: post = posts[0] f_date = datetime.strptime(post["date"], "%Y-%m-%d %H:%M:%S %Z") post["formated_date"] = f_date.strftime("%B %d, %Y") path_to_here = os.path.abspath(os.path.dirname(__file__)) f = open("{0}/static/templates/blog-post-{1}.html".format(path_to_here, post["type"]), "r") f_data = f.read() f.close() compiler = Compiler() template = compiler.compile(unicode(f_data)) context["post_data"] = template(post) context["post_title"] = post["title"] return render(request, "blog-post.html", context)
def search_string(self): """" Returns the JSON string that LendingClub expects for it's search """ self.__normalize() # Get the template tmpl_source = unicode(open(self.tmpl_file).read()) # Process template compiler = Compiler() template = compiler.compile(tmpl_source) out = template(self) if not out: return False out = ''.join(out) # # Cleanup output and remove all extra space # # remove extra spaces out = re.sub('\n', '', out) out = re.sub('\s{3,}', ' ', out) # Remove hanging commas i.e: [1, 2,] out = re.sub(',\s*([}\\]])', '\\1', out) # Space between brackets i.e: ], [ out = re.sub('([{\\[}\\]])(,?)\s*([{\\[}\\]])', '\\1\\2\\3', out) # Cleanup spaces around [, {, }, ], : and , characters out = re.sub('\s*([{\\[\\]}:,])\s*', '\\1', out) return out
def blog_post(request, post_id): if settings.BLOG_PLATFORM == 'tumblr': r = requests.get('{0}/posts?api_key={1}&id={2}'.format( settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id)) if r.status_code == 200: post_response = r.json().get('response', {}) posts = post_response.get('posts', []) if posts: post = posts[0] f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z') post['formated_date'] = f_date.strftime('%B %d, %Y') elif settings.BLOG_PLATFORM == 'wordpress': r = requests.get('{0}/posts/{1}'.format(settings.WORDPRESS_API_URL, post_id)) if r.status_code == 200: # Get Wordpress response into the same format as Tumblr so we can # reuse Handlebars template post = r.json() convertWordpressResponse(post) # At this point we should have a post dict from either Tumblr or Wordpress post['disqus_enabled'] = settings.DISQUS_INTEGRATION_ENABLED if settings.SHARETHIS_PUBLISHER_KEY: post['sharethis_enabled'] = True path = '{0}/static/templates/blog-post-{1}.html'.format( os.path.join(os.path.dirname(__file__), '..'), post['type']) with open(path, 'r') as f: f_data = f.read() compiler = Compiler() template = compiler.compile(unicode(f_data)) context = dict() context['post_data'] = template(post) alt_title = '' if (post['type'] == 'photo' or post['type'] == 'video'): alt_title = '{0}: {1}'.format(post['type'].capitalize(), post['caption'][3:-4]) elif (post['type'] == 'quote'): alt_title = '{0}: {1}'.format(post['type'].capitalize(), post['text']) elif (post['type'] == 'audio'): alt_title = '{0}: {1} - {2}'.format(post['type'].capitalize(), post['artist'], post['track_name']) context['post_title'] = post.get('title', unescape(alt_title)) if post['type'] == 'text' and post['body']: context['meta_description'] = strip_tags(post['body'])[:150] if post['tags']: context['meta_keywords'] = ', '.join(post['tags']) return render(request, 'blog-post.html', context)
def applySwap(KeyPairs, File): Template_File = open(File, 'r') with Template_File: source = Template_File.read() compiler = Compiler() template = compiler.compile(source) Swapped = template(KeyPairs) return Swapped
def test_compile_with_path(self): template = u"Hi {{name}}!" context = { 'name': 'Ahmed' } result = u"Hi Ahmed!" path = '/project/widgets/templates' compiler = Compiler() # compile and check that speficified path is used self.assertEqual(result, compiler.compile(template, path=path)(context)) self.assertTrue(sys.modules.get('pybars._templates._project_widgets_templates') is not None) # recompile and check that a new path is used self.assertEqual(result, compiler.compile(template, path=path)(context)) self.assertTrue(sys.modules.get('pybars._templates._project_widgets_templates_1') is not None)
def test_process_templates(self): config = "{{#if A}}{{B}}{{/if}}" values = {"A": "true", "B": "XYZ"} compiler = Compiler() template = compiler.compile(config) assert "XYZ" == template(values)
def analyseAndRender(dataLocation, templateLocation, optionsLocation=""): global df if optionsLocation != "": with open(optionsLocation) as json_file: options = json.load(json_file) # For local csv if ".csv" in dataLocation and "https://docs.google.com" not in dataLocation: df = _makeDataFrame(dataLocation) # For google sheets as csv elif "https://docs.google.com" in dataLocation: print("It's a google sheet") # If its already a dataframe else: df = dataLocation with io.open(templateLocation, 'r', encoding='utf-8') as tempSource: compiler = Compiler() template = compiler.compile(tempSource.read()) helpers = { "getCellByNumber": getCellByNumber, "getCellByLabel": getCellByLabel, "checkDifferenceBetweenValues": checkDifferenceBetweenValues, "checkAgainstRollingMean": checkAgainstRollingMean, "getRollingMean": getRollingMean, "getDifference": getDifference, "sortAscending": sortAscending, "sortDescending": sortDescending, "getRankedItemDescending": getRankedItemDescending, "sumAcrossAllCols": sumAcrossAllCols, "totalSumOfAllCols": totalSumOfAllCols, "formatNumber": formatNumber, "groupBy": groupBy, "groupByTime": groupByTime, "filterBy": filterBy, "summariseCol": summariseCol, "checkDifferenceBetweenResults": checkDifferenceBetweenResults, "uniqueValues": uniqueValues, "summariseColByTimePeriod": summariseColByTimePeriod, "makeList": makeList } output = template(df, helpers=helpers) # String replacements if optionsLocation != "": if 'replacements' in options: output = _replaceStrings(options['replacements'], output) # print(output.encode('utf-8')) return output
def timeline_template(): """Returns a compiled handlebars template (as a function), which can be called on an input data object to produce HTML """ compiler = Compiler() with open("timeline_view.handlebars", "r", encoding="utf8") as f: raw_template = f.read() template = compiler.compile(raw_template) return template
def _initTemplate(self): # # Load the template # self.config.logger.info("Reading template file 'email_html_template.mustache'...") f = codecs.open("email_html_template.mustache", encoding='utf-8', mode='rb') strtempl = f.read() f.close() # # Compile the template # from pybars import Compiler compiler = Compiler() self.html_full_results_template = compiler.compile(strtempl) self.email_html_template = compiler.compile(strtempl)
def blog_post(request, post_id): if settings.BLOG_PLATFORM == 'tumblr': r = requests.get('{0}/posts?api_key={1}&id={2}'.format( settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id)) if r.status_code == 200: post_response = r.json().get('response', {}) posts = post_response.get('posts', []) if posts: post = posts[0] f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z') post['formated_date'] = f_date.strftime('%B %d, %Y') elif settings.BLOG_PLATFORM == 'wordpress': r = requests.get('{0}/posts/{1}'.format( settings.WORDPRESS_API_URL, post_id)) if r.status_code == 200: # Get Wordpress response into the same format as Tumblr so we can # reuse Handlebars template post = r.json() convertWordpressResponse(post) # At this point we should have a post dict from either Tumblr or Wordpress post['disqus_enabled'] = settings.DISQUS_INTEGRATION_ENABLED if settings.SHARETHIS_PUBLISHER_KEY: post['sharethis_enabled'] = True path = '{0}/static/templates/blog-post-{1}.html'.format( os.path.join(os.path.dirname(__file__), '..'), post['type']) with open(path, 'r') as f: f_data = f.read() compiler = Compiler() template = compiler.compile(unicode(f_data)) context = dict() context['post_data'] = template(post) alt_title = '' if (post['type'] == 'photo' or post['type'] == 'video'): alt_title = '{0}: {1}'.format(post['type'].capitalize(), post['caption'][3:-4]) elif (post['type'] == 'quote'): alt_title = '{0}: {1}'.format(post['type'].capitalize(), post['text']) elif (post['type'] == 'audio'): alt_title = '{0}: {1} - {2}'.format(post['type'].capitalize(), post['artist'], post['track_name']) context['post_title'] = post.get('title', unescape(alt_title)) if post['type'] == 'text' and post['body']: context['meta_description'] = strip_tags(post['body'])[:150] if post['tags']: context['meta_keywords'] = ', '.join(post['tags']) return render(request, 'blog-post.html', context)
def output_pdf(self, pdf_name): self.prepare_invoice_items() with codecs.open(self.template, encoding="utf-8") as index_file: html_text = index_file.read() compiler = Compiler() template = compiler.compile(html_text) html_text = template(self.document_data) weasytemplate = HTML(string=html_text, base_url="template/index.html") weasytemplate.write_pdf(pdf_name)
def map_template(self, *args): source = self.get_data(args[0]['id']) # print(source) abs_file_path = os.path.join(os.path.dirname(__file__), '../../templates/report.html') with open(abs_file_path) as data_file: data = data_file.read() compiler = Compiler() template = compiler.compile(data) output = template(source) return output
def generate(self, data, templateLocation): compiler = Compiler() source = open(templateLocation).read().decode('utf-8') template = compiler.compile(source) output = template(data) parser = etree.XMLParser(remove_blank_text=True) root = etree.XML(output, parser) xml_output = etree.tostring(root, pretty_print = True, xml_declaration = True, encoding='UTF-8') artifactObj = Artifact(xml_output) return artifactObj
def test_compile_with_path(self): template = u"Hi {{name}}!" context = {'name': 'Ahmed'} result = u"Hi Ahmed!" path = '/project/widgets/templates' compiler = Compiler() # compile and check that speficified path is used self.assertEqual(result, compiler.compile(template, path=path)(context)) self.assertTrue( sys.modules.get('pybars._templates._project_widgets_templates') is not None) # recompile and check that a new path is used self.assertEqual(result, compiler.compile(template, path=path)(context)) self.assertTrue( sys.modules.get('pybars._templates._project_widgets_templates_1') is not None)
def _initTemplate(self): # # Load the template # self.config.logger.info( "Reading template file 'email_html_template.mustache'...") f = codecs.open("email_html_template.mustache", encoding='utf-8', mode='rb') strtempl = f.read() f.close() # # Compile the template # from pybars import Compiler compiler = Compiler() self.html_full_results_template = compiler.compile(strtempl) self.email_html_template = compiler.compile(strtempl)
def renderTemplate(templateFileName, nameValueData): compiler = Compiler() with codecs.open(templateFileName, encoding='utf-8') as f: templateString = f.read() handlebarsTemplate = compiler.compile(templateString) # remember functionality of helpers and partials # see https://github.com/wbond/pybars3 from pybarscustom import _equal, _urlify, _languageRadioPartial, _getLanguageTitleInNativeLanguage helpers = {'equal': _equal, 'urlify': _urlify, 'getLanguageTitle' : _getLanguageTitleInNativeLanguage} languageRadioPartial = compiler.compile(_languageRadioPartial()) partials = { 'languageRadio' : languageRadioPartial} render = handlebarsTemplate(nameValueData, helpers = helpers, partials = partials) return render
class PybarMustacheRemover: def __init__(self): self.tmplt_compiler = PybarCompiler() def clean_template(self, filepath, placeholder): with open(filepath, 'r') as src_file: template_content = text_type(src_file.read()) try: compiled_template = self.tmplt_compiler.compile(template_content) return compiled_template(PybarPlaceholderContext(placeholder)) except PybarsError as error: raise_from( MustacheSubstitutionFail( 'For HTML template file {}: {}'.format(filepath, error)), error)
def generate(self, data, templateLocation): compiler = Compiler() source = open(templateLocation).read().decode('utf-8') template = compiler.compile(source) output = template(data) parser = etree.XMLParser(remove_blank_text=True) root = etree.XML(output, parser) xml_output = etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='UTF-8') artifactObj = Artifact(xml_output) return artifactObj
def render_post_json(posts, images_per_row=2, max_width=512, template_file='post.hb'): fb_posts = [] post_idx = 0 for post_id, created_time, message, images, locations, places, tags in posts: post_idx = post_idx + 1 post_images = [] for i in range(0, len(images)): image = images[i] if image.get('src'): image_url = image['src'] image_url_hash = hashlib.md5( image_url.encode()).hexdigest() GhostImporter._resize_image(image) post_image = { 'filename': image_url_hash, 'width': image['width'], 'height': image['height'], 'src': image_url, 'row': int(i / images_per_row) } post_images.append(post_image) message_lines = [ m for m in message.replace('"', '').splitlines() if m.strip() ] if message else [] fb_post = { 'date': re.sub(" .*", "", created_time), 'message': message_lines, 'has_image': len(post_images) > 0, 'has_locations': locations and len(locations) > 0, 'gallery_idx': post_idx, 'images': post_images, 'locations': ",".join(locations) if locations else None, 'places': places, 'tags': [("with " + ", ".join(tags))] if tags else None } fb_posts.append(fb_post) compiler = Compiler() template_source = open(template_file, 'r').read() template = compiler.compile(template_source) output = template({'fb_posts': fb_posts}) return output
def render(input_file, value_file, output_file, enable_env): with open(input_file, encoding="utf-8") as inputF: source = inputF.read() with open(value_file) as valueF: values = json.load(valueF) if enable_env: for k, v in os.environ.iteritems(): values[k] = v compiler = Compiler() template = compiler.compile(source) output = template(values, helpers={"eq": eq}) with open(output_file, "w+") as outputF: outputF.write(output)
def __get_compiled_template(self, template_name): template_path = self.__get_template_path(template_name) try: from pybars import Compiler except ImportError as e: Compiler = None logger.debug(str(e)) logger.warning( "Unable to load pybars; install pybars3 to load profile directly from the current session " ) with open(template_path, "r") as file_with_template: source = file_with_template.read() compiler = Compiler() template = compiler.compile(source) return template
def cli(template, source, outputdir, pagename): outputdir = Path(outputdir) outputdir.mkdir(parents=True, exist_ok=True) df = pd.read_csv(source) compiler = Compiler() template = compiler.compile(open(template).read()) with open(outputdir / "index.html", "w") as f: f.write( template( { "data": df, "dataPerVoltage": { voltage: dataToTable( df[df["Input voltage @ V"] == voltage]) for voltage in df["Input voltage @ V"].unique() }, "pageName": pagename }, helpers=buildHelpers(outputdir, df)))
def generate_manifests(template_vars: Dict[str, str], dest: Path) -> None: """Given template_vars, a dict from template variable name to the value for that variable, recursively find all files under K8_DIR, expand them as handlebars templates if they have a .tmpl.yml extension, and copy them to the same relative location in dest. Files found under K8_DIR that do not end with .tmpl.yml are copied unchanged to dest. """ compiler = Compiler() TEMPLATE_SUFFIX = '.tmpl.yml' # As we walk cur_dir we'll find additional subdirectories which we'll push here to be explored in later iterations. to_explore: List[Path] = [K8_DIR.absolute()] while len(to_explore) > 0: cur_dir = to_explore.pop().absolute() log.info('Looking for Kubernetes files and templates in %s', cur_dir) for file_or_dir in cur_dir.iterdir(): if file_or_dir.is_dir(): to_explore.append(file_or_dir) else: dest_file = dest / file_or_dir.absolute().relative_to( K8_DIR.absolute()) dest_file.parent.mkdir(parents=True, exist_ok=True) if str(file_or_dir).endswith(TEMPLATE_SUFFIX): dest_file = dest_file.parent / ( dest_file.name[:-len(TEMPLATE_SUFFIX)] + '.yml') log.info('Expanding template %s to %s', file_or_dir, dest_file) with open(file_or_dir, 'rt', encoding='utf-8') as inf: contents = inf.read() template = compiler.compile(contents) out_contents = template(template_vars) with open(dest_file, 'wt', encoding='utf-8') as outf: outf.write(out_contents) else: log.info('Copying %s to %s', file_or_dir, dest_file) shutil.copy(file_or_dir, dest_file)
def run(self, data): compiler = Compiler() with open(self.config['template'], 'r') as tmpl: template = compiler.compile(tmpl.read()) return template({'data': data, 'count': len(data)})