本文整理汇总了Python中pystache.renderer.Renderer.render方法的典型用法代码示例。如果您正苦于以下问题:Python Renderer.render方法的具体用法?Python Renderer.render怎么用?Python Renderer.render使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pystache.renderer.Renderer
的用法示例。
在下文中一共展示了Renderer.render方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def render(template, context=None, **kwargs):
"""
Return the given template string rendered using the given context.
"""
renderer = Renderer()
return renderer.render(template, context, **kwargs)
示例2: test
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
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.
# TODO: make this section of code easier to understand.
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
renderer = Renderer(partials=partials)
actual = renderer.render(template, new_data)
actual = actual.encode('utf-8')
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)
示例3: render
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def render(template, context=None, name=None, **kwargs):
"""
Return the given template string rendered using the given context.
"""
renderer = Renderer()
parsed_template = parse(template, name=name)
return renderer.render(parsed_template, context, **kwargs)
示例4: crear_plantilla
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def crear_plantilla(archivo_fuente='user.c'):
print "creando plantilla para archivo %s" % archivo_fuente
renderer = Renderer()
template = renderer.load_template(SOURCE_TEMPLATE)
dato_plantilla = renderer.render(template, {'include_path': archivo_fuente})
archivo = open(SOURCE_FILE, 'w')
archivo.write(dato_plantilla)
archivo.close()
print "plantilla creada"
示例5: main
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def main(sys_argv=sys.argv):
template, context, c_format, multiple = parse_args(sys_argv, USAGE)
if template.endswith('.mustache'):
template = template[:-9]
renderer = Renderer()
try:
template = renderer.load_template(template)
except TemplateNotFoundError:
pass
if context.endswith(".csv") or (c_format and (c_format == "csv")):
try:
context = csv.DictReader(open(context, 'rb'))#, delimiter=',', quotechar='"')
except IOError:
print('ERROR: Could not parse context as CSV file. Check usage for input format options')
exit(-1)
else:
try:
context = json.load(open(context))
except IOError:
context = json.loads(context)
except ValueError: #likely a not well-formed JSON string, or user forgot -f csv.
print('ERROR: Could not parse context as JSON file or text, check usage for input format options')
exit(1)
if (multiple):
print ("multiple render on field %s" % multiple)
fileName, fileExt = os.path.splitext(multiple)
for i,c in enumerate(context):
if multiple in c:
f_name = str(c[multiple])
else:
f_name = "%s-%03d%s" % (fileName, i, fileExt)
with open(f_name, "w") as f: # mode "wx" could be used to prevent overwriting, + pass IOError, adding "--force" option to override.
rendered = renderer.render(template, c)
f.write(rendered)
print ("%s done") % f_name
else:
rendered = renderer.render(template, context)
print rendered
示例6: get
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def get(self):
pass_phrase = self.authenticate_request()
if pass_phrase:
if self.check_setup():
loader = Loader(extension='html', search_dirs=['view', 'view/setup'])
renderer = Renderer(file_extension='html',
search_dirs=['view/partials', 'view/setup'])
template = loader.load_name('setup')
html = renderer.render(template, {"pass": pass_phrase})
self.write(html)
else:
self.write("setup already completed.")
示例7: get
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def get(self, article_name):
article_name = article_name.lower()
if article_name in BaseController.articles:
article = BaseController.articles[article_name]
# if content has not modified since last request
# send a 304 not modified status
modified_header_key = "If-Modified-Since"
if modified_header_key in self.request.headers:
if (self.request.headers["If-Modified-Since"] ==
article['modified_date']):
self.set_status(304)
return
if (BaseController.settings['enable_caching'] and
article_name in BaseController.cached_articles):
html = BaseController.cached_articles[article_name]
else:
view_model = {
"article": article,
"site_name": BaseController.settings['site_name']
}
self.attach_meta_data(view_model)
loader = Loader(file_encoding='utf8',
extension='html',
search_dirs=['view', ])
renderer = Renderer(file_encoding='utf8',
file_extension='html',
search_dirs=['view/partials'])
template = loader.load_name('article')
html = renderer.render(template, view_model)
# cache the html
BaseController.cached_articles[article_name] = html
# set http caching headers
if "http_caching_max_age" in BaseController.settings:
max_age = BaseController.settings["http_caching_max_age"]
else:
max_age = 60
self.set_header("Cache-control", "max-age=%s" % max_age)
self.set_header("Last-Modified", article['modified_date'])
self.write(html)
else:
raise tornado.web.HTTPError(404)
示例8: generate_page
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def generate_page(self, articles):
view_model = {
"articles": articles,
"site_name": BaseController.settings["site_name"]
}
self.attach_meta_data(view_model)
loader = Loader(file_encoding='utf8', extension='html',
search_dirs=['view', ])
renderer = Renderer(file_encoding='utf8', file_extension='html',
search_dirs=['view/partials'])
template = loader.load_name('list')
html = renderer.render(template, view_model)
return html
示例9: render
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def render(self, content, data):
"""
Render the given ``content`` as template with the ``data`` dictionary.
Args:
content (str): The template content to render.
data (dict): The data dictionary to render.
Returns:
str: The rendered template text
"""
stache = Renderer(partials=self._partials_loader)
return stache.render(content, data)
示例10: render
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def render(self, data_dict, template):
"""
Take a data dictionary and render it using the given template file.
Required Arguments:
:param data_dict: The data dictionary to render.
:param template: The path to the template, after the
``template_module`` or ``template_dirs`` prefix as defined in the
application.
:returns: str (the rendered template text)
"""
LOG.debug("rendering output using '%s' as a template." % template)
content = self.load_template(template)
stache = Renderer(partials=self._partials_loader)
return stache.render(content, data_dict)
示例11: main
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def main(sys_argv=sys.argv):
template, context = parse_args(sys_argv, USAGE)
if template.endswith('.mustache'):
template = template[:-9]
renderer = Renderer()
try:
template = renderer.load_template(template)
except IOError:
pass
try:
context = json.load(open(context))
except IOError:
context = json.loads(context)
rendered = renderer.render(template, context)
print rendered
示例12: main
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def main(argv=None):
if argv is None:
argv = sys.argv
template, context, options = parse_args(argv, USAGE)
if context is None and not sys.stdin.isatty():
user_context, _ = read_yaml_frontmatter(sys.stdin)
elif context:
content = arg2text(context)
user_context, _ = extract_context(content, greedy=True)
else:
user_context = {}
# assuming first arg is a filename or template literal
template = arg2text(template)
template_context, template = extract_context(template)
template_context.update(user_context)
renderer = Renderer()
rendered = renderer.render(template, template_context)
print(rendered.encode('utf-8'))
示例13: _runTest
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def _runTest(self):
context = self._context
description = self._description
expected = self._expected
file_path = self._file_path
partials = self._partials
template = self._template
test_name = self._test_name
renderer = Renderer(partials=partials)
actual = renderer.render(template, context)
# We need to escape the strings that occur in our format string because
# they can contain % symbols, for example (in delimiters.yml)--
#
# "template: '{{=<% %>=}}(<%text%>)'"
#
def escape(s):
return s.replace("%", "%%")
parser_info = _get_parser_info()
subs = [repr(test_name), description, os.path.abspath(file_path),
template, repr(context), parser_info]
subs = tuple([escape(sub) for sub in subs])
# We include the parsing module version info to help with troubleshooting
# yaml/json/simplejson issues.
message = """%s: %s
File: %s
Template: \"""%s\"""
Context: %s
%%s
[using %s]
""" % subs
self.assertString(actual, expected, format=message)
示例14: get
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def get(self):
if (BaseController.settings['enable_caching'] and
BaseController.cached_home):
html = BaseController.cached_home
self.write(html)
else:
published_articles = []
for article in BaseController.articles.values():
if article['date'] is not None:
published_articles.append(article)
articles = sorted(published_articles,
key=operator.itemgetter("date"),
reverse=True)
max_articles_count = BaseController.settings["homepage_max_articles"]
show_archive = False
if len(articles) > max_articles_count:
show_archive = True
articles = articles[0:max_articles_count]
view_model = {
"articles": articles,
"showArchive": show_archive,
"site_name": BaseController.settings["site_name"]
}
self.attach_meta_data(view_model)
loader = Loader(file_encoding='utf8', extension='html',
search_dirs=['view', ])
renderer = Renderer(file_encoding='utf8', file_extension='html',
search_dirs=['view/partials'])
template = loader.load_name('home')
html = renderer.render(template, view_model)
# cache the home page
BaseController.cached_home = html
self.write(html)
示例15: test
# 需要导入模块: from pystache.renderer import Renderer [as 别名]
# 或者: from pystache.renderer.Renderer import render [as 别名]
def test(self):
template = testData['template']
partials = testData.has_key('partials') and testData['partials'] or {}
expected = testData['expected']
data = testData['data']
renderer = Renderer(partials=partials)
actual = renderer.render(template, data)
actual = actual.encode('utf-8')
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)