def render(self, template_name, context={}, index=None): """ Given a template name, pick a template and render it with the provided context. :param template_name: the name of a template group. :param context: dictionary representing values to be rendered :param index: optional, the specific index in the collection of templates :raises NotImplementedError: if no template can be found identified by template_name :return: """ if template_name not in self.templates: raise NotImplementedError("Template not found: %s" % template_name) template_functions = self.templates.get(template_name) if index is None: index = random.randrange(len(template_functions)) else: index %= len(template_functions) return mustache.render(template_functions[index], context)
def test(self): template = testData['template'] partials = testData.has_key('partials') and testData['partials'] or {} expected = testData['expected'] data = testData['data'] # Convert code strings to functions. new_data = {} for key, val in data.iteritems(): if isinstance(val, dict) and val.get('__tag__') == 'code': val = eval(val['python']) new_data[key] = val actual = render(template, new_data, partials) message = """%s Template: \"""%s\""" Expected: %s Actual: %s Expected: \"""%s\""" Actual: \"""%s\""" """ % (description, template, repr(expected), repr(actual), expected, actual) self.assertEquals(actual, expected, message)
def test_non_strings(self): template = "{{#stats}}({{key}} & {{value}}){{/stats}}" stats = [] stats.append({'key': 123, 'value': ['something']}) stats.append({'key': u"chris", 'value': 0.900}) ret = mustache.render(template, { 'stats': stats }) self.assertEquals(ret, """(123 & ['something'])(chris & 0.9)""")
def render_template(name, context): template = open(os.path.join(TEMPLATES_ROOT, name), 'r').read() partials = { 'header': open(os.path.join(TEMPLATES_ROOT, 'header.html')).read(), 'footer': open(os.path.join(TEMPLATES_ROOT, 'footer.html')).read(), } return mustache.render(template, context, partials=partials)
def __spec_test(self, test_suite): with open(self.PATH.format(test_suite), 'r') as fp: suite = json.loads(fp.read()) tests = suite['tests'] for test in tests: template = mustache.build(test['template'], test.get('partials')) result = mustache.render(template, test['data']) msg = '{}: {} != {}'.format(test['desc'], repr(str(test['expected'])), repr(str(result))) self.assertEqual(result, test['expected'], msg)
def test_even_less_basic(self): template = "I think {{name}} wants a {{thing}}, right {{name}}?" ret = mustache.render(template, { 'name': 'Jon', 'thing': 'racecar' }) self.assertEquals(ret, "I think Jon wants a racecar, right Jon?")
def test_interpolation_18(self): template = u'"{{a.b.c}}" == ""' template = mustache.build(template, partials=None) context = {u'a': {}} rendered = mustache.render(template, context) self.assertEqual(rendered, u'"" == ""')
def test_interpolation_10(self): template = u'"{{&power}} jiggawatts!"' template = mustache.build(template, partials=None) context = {u'power': 1.21} rendered = mustache.render(template, context) self.assertEqual(rendered, u'"1.21 jiggawatts!"')
def test_sections(self): template = """<ul>{{#users}}<li>{{name}}</li>{{/users}}</ul>""" context = { 'users': [ {'name': 'Chris'}, {'name': 'Tom'}, {'name': 'PJ'} ] } ret = mustache.render(template, context) self.assertEquals(ret, """<ul><li>Chris</li><li>Tom</li><li>PJ</li></ul>""")
def test_unicode(self): template = 'Name: {{name}}; Age: {{age}}' ret = mustache.render(template, { 'name': u'Henri Poincaré', 'age': 156 }) self.assertEquals(ret, u'Name: Henri Poincaré; Age: 156')
def test_true_sections_are_shown(self): template = "Ready {{#set}}set{{/set}} go!" ret = mustache.render(template, { 'set': True }) self.assertEquals(ret, "Ready set go!")
def test_comments(self): template = "What {{! the }} what?" ret = mustache.render(template, {}) self.assertEquals(ret, "What what?")
def test_partials_9(self): template = u'\\\n {{>partial}}\n/\n' template = mustache.build(template, partials={u'partial': u'|\n{{{content}}}\n|\n'}) context = {u'content': u'<\n->'} rendered = mustache.render(template, context) self.assertEqual(rendered, u'\\\n |\n <\n->\n |\n/\n')
def test_partials_8(self): template = u'>\n {{>partial}}' template = mustache.build(template, partials={u'partial': u'>\n>'}) context = {} rendered = mustache.render(template, context) self.assertEqual(rendered, u'>\n >\n >')
def test_interpolation_29(self): template = u'|{{& string }}|' template = mustache.build(template, partials=None) context = {u'string': u'---'} rendered = mustache.render(template, context) self.assertEqual(rendered, u'|---|')
def test_partials_0(self): template = u'"{{>text}}"' template = mustache.build(template, partials={u'text': u'from partial'}) context = {} rendered = mustache.render(template, context) self.assertEqual(rendered, u'"from partial"')
def test_interpolation_20(self): template = u'"{{#a}}{{b.c.d.e.name}}{{/a}}" == "Phil"' template = mustache.build(template, partials=None) context = {u'a': {u'b': {u'c': {u'd': {u'e': {u'name': u'Phil'}}}}}, u'b': {u'c': {u'd': {u'e': {u'name': u'Wrong'}}}}} rendered = mustache.render(template, context) self.assertEqual(rendered, u'"Phil" == "Phil"')
def test_interpolation_19(self): template = u'"{{a.b.c.name}}" == ""' template = mustache.build(template, partials=None) context = {u'a': {u'b': {}}, u'c': {u'name': u'Jim'}} rendered = mustache.render(template, context) self.assertEqual(rendered, u'"" == ""')
def test_ignores_misses(self): template = "I think {{name}} wants a {{thing}}, right {{name}}?" ret = mustache.render(template, { 'name': 'Jon' }) self.assertEquals(ret, "I think Jon wants a , right Jon?")
def test_partials_10(self): template = u'|{{> partial }}|' template = mustache.build(template, partials={u'partial': u'[]'}) context = {u'boolean': True} rendered = mustache.render(template, context) self.assertEqual(rendered, u'|[]|')
def test_render_zero(self): template = 'My value is {{value}}.' ret = mustache.render(template, { 'value': 0 }) self.assertEquals(ret, 'My value is 0.')
def test_inverted_1(self): template = u'"{{^boolean}}This should not be rendered.{{/boolean}}"' template = mustache.build(template, partials=None) context = {u'boolean': True} rendered = mustache.render(template, context) self.assertEqual(rendered, u'""')
def test_false_sections_are_hidden(self): template = "Ready {{#set}}set {{/set}}go!" ret = mustache.render(template, { 'set': False }) self.assertEquals(ret, "Ready go!")
def test_inverted_2(self): template = u'"{{^context}}Hi {{name}}.{{/context}}"' template = mustache.build(template, partials=None) context = {u'context': {u'name': u'Joe'}} rendered = mustache.render(template, context) self.assertEqual(rendered, u'""')
def test_interpolation_13(self): template = u'I ({{&cannot}}) be seen!' template = mustache.build(template, partials=None) context = {} rendered = mustache.render(template, context) self.assertEqual(rendered, u'I () be seen!')
summary = [] for team in teams: odds = team[2:] max_ = max(odds) min_ = min(odds) mean = np.mean(odds) median = np.median(odds) twentyfive = np.percentile(odds, 25) seventyfive = np.percentile(odds, 75) summary.append(team[:2] + [max_, min_, mean, median, twentyfive, seventyfive]) summaryfile = "raw/summary%s.csv" % timestamp with file(summaryfile, 'w') as outfile: w = csv.writer(outfile) w.writerow([ 'name', 'group', 'max', 'min', 'mean', 'median', 'twentyfive', 'seventyfive' ]) for row in summary: w.writerow(row) shutil.copy2(summaryfile, "summary.csv") last_updated = time.strftime("%b %d %Y %H:%M") context = {"last_updated": last_updated} out = mustache.render(file("index.mustache.html").read(), context) file("index.html", 'w').write(out)
def test_basic(self): ret = mustache.render("Hi {{thing}}!", { 'thing': 'world' }) self.assertEquals(ret, "Hi world!")
def web_page(self, date: datetime.date) -> str: rows = [] # type: List[Dict[str,str]] tx1 = self.ac1.indexable(date) tx2 = self.ac2.indexable(date) while not tx1.done() or not tx2.done(): row_class = "rowEven" if len(rows) % 2 == 0 else "rowed" top = True # add to top of page? if tx1.done(): print("col 1 done") col1 = "<br>".join(self.ac1.get_similar_txs(tx2.curr())) col2 = '<font color="red">%s</font>' % tx2.curr().as_beancount( ) col2 += tx2.curr().html() tx2.next() elif tx2.done(): print("col 2 done") col1 = '<font color="red">%s</font>' % tx1.curr().as_beancount( ) col1 += f"<br />{tx1.curr().html()}" col2 = "<br>".join(self.ac2.get_similar_txs(tx1.curr())) tx1.next() elif tx1.curr()["amount"] == tx2.curr()["amount"]: print("col1 == col2") top = False col1 = tx1.curr().html() col2 = tx2.curr().html() tx1.next() tx2.next() elif tx1.curr()["amount"] > tx2.curr()["amount"]: print("col1 > col2") col1 = '<font color="red">%s</font>' % tx1.curr().as_beancount( ) col1 += f"<br />{tx1.curr().html()}" col2 = "<br>".join(self.ac2.get_similar_txs(tx1.curr())) tx1.next() elif tx1.curr()["amount"] < tx2.curr()["amount"]: print("col1 < col2") col1 = tx2.curr().html() col1 = "<br>".join(self.ac1.get_similar_txs(tx2.curr())) col2 = '<font color="red">%s</font>' % tx2.curr().as_beancount( ) tx2.next() dat = {"row_class": row_class, "col1": col1, "col2": col2} # Add matched transactions to the bottom of the page, and # unmatched to the top, so they'll get noticed easier and # not require scrolling. if top: rows = [dat] + rows else: rows.append(dat) # Render and write it out body_dat = { "date": date, "col1_total": sum([tx["amount"] for tx in tx1]), "col2_total": sum([tx["amount"] for tx in tx2]), "rows": rows, } body = mustache.render(self.templates, "reconcile_body", body_dat) return mustache.render(self.templates, "master", {"body": body})
def test_implicit_iterator(self): template = """<ul>{{#users}}<li>{{.}}</li>{{/users}}</ul>""" context = { 'users': [ 'Chris', 'Tom','PJ' ] } ret = mustache.render(template, context) self.assertEquals(ret, """<ul><li>Chris</li><li>Tom</li><li>PJ</li></ul>""")
def test_less_basic(self): template = "It's a nice day for {{beverage}}, right {{person}}?" ret = mustache.render(template, { 'beverage': 'soda', 'person': 'Bob' }) self.assertEquals(ret, "It's a nice day for soda, right Bob?")
t.append(o) fixed.append(t) teams = fixed summary = [] for team in teams: odds = team[2:] max_ = max(odds) min_ = min(odds) mean = np.mean(odds) median = np.median(odds) twentyfive = np.percentile(odds, 25) seventyfive = np.percentile(odds, 75) summary.append(team[:2] + [max_, min_, mean, median, twentyfive, seventyfive]) summaryfile = "raw/summary%s.csv" % timestamp with file(summaryfile, 'w') as outfile: w = csv.writer(outfile) w.writerow(['name', 'country', 'max', 'min', 'mean', 'median', 'twentyfive', 'seventyfive']) for row in summary: w.writerow(row) shutil.copy2(summaryfile, "summary.csv") last_updated = time.strftime("%b %d %Y %H:%M") context = {"last_updated": last_updated} out = mustache.render(file("index.mustache.html").read(), context) file("index.html", 'w').write(out)
def test_interpolation_16(self): template = u'"{{&person.name}}" == "{{#person}}{{&name}}{{/person}}"' template = mustache.build(template, partials=None) context = {u'person': {u'name': u'Joe'}} rendered = mustache.render(template, context) self.assertEqual(rendered, u'"Joe" == "Joe"')