本文整理汇总了Python中pystache.render函数的典型用法代码示例。如果您正苦于以下问题:Python render函数的具体用法?Python render怎么用?Python render使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了render函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render
def render(self, data={}):
"""
Runs the raw markdown through mustache, then converts it to HTML with
markdown, and finally renders the template with the converted markdown
to produce the final page.
:param data: An optional dict of additional data that gets passed to
the mustache templates while they render.
"""
extra_tmpls = {}
data.update({"time": time,
"date": date,
"site_title": config["site_title"]})
data.update(self.page_config)
for tmpl in raw_extra_tmpls:
extra_tmpls[tmpl] = pystache.render(raw_extra_tmpls[tmpl], data)
data.update({"files": extra_tmpls})
templated_markdown = pystache.render(self.raw_markdown, data)
data["content"] = markdown(templated_markdown, extensions=['extra'])
template = self.page_config["template"] if "template" in self.page_config else "single"
template_path = whats_where["templates"] + "/" + template + extension
with open(template_path, "r") as tmpl_data:
raw_tmpl = unicode(tmpl_data.read())
self.rendered_final = pystache.render(raw_tmpl, data)
示例2: renderPost
def renderPost(post, posts):
metadata = {}
for k, v in post[0].iteritems():
metadata[k] = v[0]
metadata[u'content'] = post[1]
metadata[u'sitename'] = sitename
metadata[u'webRoot'] = webRoot
metadata[u'author'] = author
metadata[u'typekitId'] = typekitId
postName = removePunctuation(metadata[u'title'])
postName = metadata[u'date'].split(' ')[0] + '-' + postName.replace(u' ',u'-').replace(u'‑',u'-')
postName = u'-'.join(postName.split('-'))
postFileName = outputDir + postName + '.html'
metadata[u'postURL'] = webRoot + postName + '.html'
metadata[u'title'] = unicode(mdx_smartypants.unicode_entities(metadata[u'title']))
if u'link' in metadata:
templateType = u'/post-content-link.html'
else:
templateType = u'/post-content.html'
with open(templateDir + templateType,'r','utf-8') as f:
postContentTemplate = f.read()
postContent = pystache.render(postContentTemplate,metadata,decode_errors='ignore')
metadata['post-content'] = postContent
with open(templateDir + u'/post-page.html','r','utf-8') as f:
postPageTemplate = f.read()
postPageResult = pystache.render(postPageTemplate,metadata,decode_errors='ignore')
with open(postFileName,'w','utf-8') as f:
f.write(postPageResult)
return posts.append(metadata)
示例3: nanny
def nanny():
"""Nanny reciever endpoint
if recieved is post and legit json, app.config['NANNY_TEMPLATE'] is then
passed to pystache, otherwise app.config['NANNY_SCRIPT'] is used directly.
ALWAYS returns true, no questions asked
"""
data = request.get_json()
for t, p in app.config.get('NANNY_PEEK', []):
to_peek = pystache.render(t, data)
m = re.match(p, to_peek)
if not m:
logging.info('unable to match re %s with %s (from template %s)', p, to_peek, t)
abort(400)
data.update(m.groupdict())
template = app.config['NANNY_TEMPLATE']
script = pystache.render(template, request.json)
if not script.strip():
logging.info('Nanny got empty script, ignoring...')
abort(400)
logging.info('Nanny to run script: \n%s', script)
subprocess.Popen(script, shell=True)
return jsonify(status='OK')
示例4: play_or_say
def play_or_say(r, audio, **kwds):
"""
Take twilio response and play or say message from an AudioRecording
Can use mustache templates to render keyword arguments
"""
if audio:
if (hasattr(audio, 'text_to_speech') and not (audio.text_to_speech == '')):
msg = pystache.render(audio.text_to_speech, kwds)
r.say(msg)
elif (hasattr(audio, 'file_storage') and (audio.file_storage.fp is not None)):
r.play(audio.file_url())
elif type(audio) == str:
try:
msg = pystache.render(audio, kwds)
r.say(msg)
except Exception:
current_app.logger.error('Unable to render pystache template %s' % audio)
r.say(audio)
else:
current_app.logger.error('Unknown audio type %s' % type(audio))
else:
r.say('Error: no recording defined')
current_app.logger.error('Missing audio recording')
current_app.logger.error(kwds)
示例5: main
def main():
dumpPath = r'..\examples\dump.cpp.json'
projPath = r'C:\Users\paperweight\Source\Repos\Tod\Tod.vcxproj'
namespaces = ['tod']
moduleNames = ['cppcli_blanket']
modules = map(__import__, moduleNames)
pyclump.DumpAST(projPath, namespaces, dumpPath)
f = open(dumpPath, 'r')
data = f.read()
meta = json.loads(data)
f.close()
a = modules[0].Transform(meta)
a.Execute()
# TODO: transform dump.json into dump.cppcli.json into dump.<class>.h/dump.<class>.cpp/dump.csproj/dump.sln
for clas in meta:
if clas['subtype'] == 'factory':
clas['subtype'] = 'static class'
elif clas['subtype'] == 'class':
clas['subtype'] = 'ref class'
clas['projectname'] = 'tod'
f = open(r'..\templates\cppcli.pst', 'r')
template = f.read()
f.close()
outputFolder = ".\examples"
print meta
for clas in meta:
print pystache.render(template, clas)
示例6: print_summary
def print_summary(failed_builds, total_builds, html=False):
# All the templates
count = [
"{{failed}} of {{total}} regressions failed",
"<p><b>{{failed}}</b> of <b>{{total}}</b> regressions failed</p>",
]
regression_link = [
"\tRegression Link: {{link}}\n" "\tNode: {{node}}",
"<p> Regression Link: {{link}}</p>" "<p> Node: {{node}}</p>",
]
component = ["\tComponent: {{comp}}", "<p> Component: {{comp}}</p>"]
failure_count = [
"".join([TERM.red, "{{test}} ; Failed {{count}} times", TERM.normal]),
('<p><font color="red"><b>{{test}};</b> Failed <b>{{count}}' "</b> times</font></p>"),
]
template = 0
if html:
template = 1
print render(count[template], {"failed": failed_builds, "total": total_builds})
for k, v in summary.iteritems():
if k == "core":
print "".join([TERM.red, "Found cores:", TERM.normal])
for comp, link in zip(v[::2], v[1::2]):
print render(component[template], {"comp": comp})
print render(regression_link[template], {"link": link[0], "node": link[1]})
else:
print render(failure_count[template], {"test": k, "count": len(v)})
for link in v:
print render(regression_link[template], {"link": link[0], "node": link[1]})
示例7: create_post_page
def create_post_page(config,post_file_name):
project_path = config['path']
posts_folder = os.path.join(project_path,'posts')
post = [parse_post(config,os.path.join(posts_folder,post_file_name))]
if config['debug']:
url = config['path']
else:
url = config['url']
if config['disqus']['enabled']:
disqus_template = open(path.DISQUS_TEMPLATE).read()
disqus_variables = config['disqus']
disqus_variables.update({'disqus_url':url + '/pages/permalinks/' + post_file_name[:-3] + '.html',
'disqus_identifier':post_file_name[:-3]})
disqus = pystache.render(disqus_template,disqus_variables)
disqus = unicode(disqus)
else:
disqus = ''
page_content = {'posts':post,
'blog_name':config['blog_name'],
'blog_description':config['blog_description'],
'url':url,
'about_author':config['about_author'],
'contacts':config['contacts'],
'links':config['links'],
'css_file':config['css_file'],
'old_posts':get_permalinks_list(config),
'disqus':disqus,
'footage_content':config['footage_content'],
}
template = open(path.INDEX_TEMPLATE).read()
return pystache.render(template,page_content)
示例8: rendertemplate
def rendertemplate(type):
body = ''
if type == 'html':
summary = pystache.render(html_summary_tmpl, {
'total': stats['total'],
'addr': stats['addresses'],
'nodes': stats['nodes'],
'ways': stats['ways'],
'date': now.strftime("%B %d, %Y")
})
elif type == 'text':
summary = pystache.render(text_summary_tmpl, {
'total': stats['total'],
'addr': stats['addresses'],
'nodes': stats['nodes'],
'ways': stats['ways'],
'date': now.strftime("%B %d, %Y")
})
# Add summary
body+=summary
for c in cids:
if type == 'html':
header = pystache.render(html_headers_tmpl, {
'changeset': c,
})
elif type == 'text':
header = pystache.render(text_headers_tmpl, {
'changeset': c,
})
# Add header for each changeset ID
body+=header
for each in finalobject[c]:
# Add changes, grouped by tags
body+=renderChanges(each, type)
return body
示例9: send_confirmation
def send_confirmation(user, followMod=None):
with open("emails/confirm-account") as f:
if followMod != None:
message = pystache.render(
f.read(),
{
"user": user,
"site-name": _cfg("site-name"),
"domain": _cfg("domain"),
"confirmation": user.confirmation + "?f=" + followMod,
},
)
else:
message = html.parser.HTMLParser().unescape(
pystache.render(
f.read(),
{
"user": user,
"site-name": _cfg("site-name"),
"domain": _cfg("domain"),
"confirmation": user.confirmation,
},
)
)
send_mail.delay(
_cfg("support-mail"), [user.email], "Welcome to " + _cfg("site-name") + "!", message, important=True
)
示例10: generate_xmls
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)
示例11: main
def main():
url = 'http://docs.python.org/2/library/datetime.html'
body = urllib2.urlopen(url).read()
soup = BeautifulSoup(body)
table = soup.find(id='strftime-and-strptime-behavior').find('table')
example_date = datetime.datetime(2013, 12, 25, 17, 15, 30)
directives = []
for row in table.select('tbody > tr'):
tds = row.find_all('td')
directive = tds[0].find('span').string
# we use getText() here because some of the meanings have extra markup
meaning = tds[1].getText().replace('\n', ' ')
example = example_date.strftime(directive)
directives.append({
'directive': directive,
'meaning': meaning,
'example': example,
})
template = open('templates/index.html.mustache').read()
context = {
'example_date': str(example_date),
'example_date_repr': repr(example_date),
'directives': directives,
'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%d'),
}
print pystache.render(template, context).encode('utf8')
return 0
示例12: play_or_say
def play_or_say(r, audio, voice='alice', lang='en-US', **kwargs):
"""
Take twilio response and play or say message from an AudioRecording
Can use mustache templates to render keyword arguments
"""
if audio:
# check to ensure lang is in list of valid locales
if lang not in TWILIO_TTS_LANGUAGES:
if '-' in lang:
lang, country = lang.split('-')
else:
lang = 'en'
if (hasattr(audio, 'text_to_speech') and audio.text_to_speech):
msg = pystache.render(audio.text_to_speech, kwargs)
r.say(msg, voice=voice, language=lang)
elif (hasattr(audio, 'file_storage') and (audio.file_storage.fp is not None)):
r.play(audio.file_url())
elif type(audio) == str:
try:
msg = pystache.render(audio, kwargs)
r.say(msg, voice=voice, language=lang)
except pystache.common.PystacheError:
current_app.logger.error('Unable to render pystache template %s' % audio)
r.say(audio, voice=voice, language=lang)
else:
current_app.logger.error('Unknown audio type %s' % type(audio))
else:
r.say('Error: no recording defined')
current_app.logger.error('Missing audio recording')
current_app.logger.error(kwargs)
示例13: results
def results(request):
params = rewrite_params(request).copy()
del params['_escaped_fragment_']
if not len(params):
return HttpResponseNotFound()
if not params.has_key('page'): params['page'] = 1
if not params.has_key('sorting'): params['sorting'] = '_score'
query = {}
for param in params:
query[param] = urllib2.unquote(unicode(params[param]))
search = SearchHandler().create(InjectRequest(query))
loader = Loader()
items = pystache.render(
loader.load_template_source('pages/search/items.html')[0],
search['results']
)
facets = ''
if search.has_key('facets') and search['facets'].has_key('company.facet'):
facets = pystache.render(
loader.load_template_source('pages/search/facets.html')[0],
{'facets' : search['facets']['company.facet']}
)
term = ''
if (query.has_key('what') and len(query['what'])) and (query.has_key('where') and len(query['where'])):
term = '%s / %s' % (query['what'].lower(), query['where'].lower())
elif query.has_key('what'): term = query['what'].lower()
elif query.has_key('where'): term = query['where'].lower()
total = 0
if len(search['results']):
total = search['results']['total']
pagination = ''
if len(search['results']) and len(search['results']['pagination']) > 1:
pagination = pystache.render(
loader.load_template_source('pages/search/pagination.html')[0],
{'pagination' : search['results']['pagination'] }
)
content = render_to_string('pages/search.html', {
'term': term, 'total': total, 'facets': facets,
'items': items, 'pagination': pagination
}, context_instance=RequestContext(request))
return direct_to_template(request, 'base.html', {
'search': content, 'job_count': count_documents()
})
示例14: index
def index(self):
global page_template, entry_template, path
entries = glob.glob(os.path.join(entries_path, '*.entry'))
entries.sort(key = lambda x: os.path.getmtime(x), reverse = True)
content = u""
for entry in entries:
content = content + pystache.render(entry_template, entry_from_file(entry, entry == entries[-1]))
return pystache.render(page_template, {'content': content})
示例15: generate_final
def generate_final(self, context, dest=os.getcwd()):
if self.config.verbose:
scanner = Scanner(self.template, self.templates)
keys = scanner.scan()
for key in keys:
if key in context:
if callable(context[key]):
print "%s: %s" % (key, context[key]())
else:
print "%s: %s" % (key, context[key])
source = os.path.join(self.templates, self.template)
import tempfile, time
tmp_dest = os.path.join(tempfile.gettempdir(), str(int(time.time())))
# copy to temp destination
self.merge_folder(source, tmp_dest)
os.remove(os.path.join(tmp_dest, "description.yml"))
os.remove(os.path.join(tmp_dest, "dynamic.py"))
# render content
for root, dirs, files in os.walk(tmp_dest):
if files:
for name in files:
with open(os.path.join(root, name), 'r+') as f:
print "rendering %s ..." % os.path.join(root, name)
template = unicode(f.read(), "UTF-8")
f.seek(0)
f.truncate()
f.write(pystache.render(template, context).encode("UTF-8"))
# folder names
for root, dirs, files in os.walk(tmp_dest):
if dirs:
for dir_ in map(lambda i: os.path.join(root, i), dirs):
parsed = pystache.parser.parse(unicode(dir_, "UTF-8"))
if any(hasattr(item, 'key') for item in parsed._parse_tree):
new_dir = os.path.join(root, pystache.render(dir_, context))
if not os.path.exists(new_dir):
os.makedirs(new_dir)
for template in os.listdir(dir_):
shutil.copy(os.path.join(dir_, template), new_dir)
shutil.rmtree(dir_)
# file names
for root, dirs, files in os.walk(tmp_dest):
if files:
for f in map(lambda i: os.path.join(root, i), files):
parsed = pystache.parser.parse(unicode(f, "UTF-8"))
if any(hasattr(item, 'key') for item in parsed._parse_tree):
# rename
os.rename(f, pystache.render(parsed, context))
self.merge_folder(tmp_dest, dest)