template: add a utility function to render template

Summary:
The added method takes an environment (`props`), and a program written in
the template language, execute the program, and pass output to `ui.write`.

The API is similar to the upstream [1]. But it avoids `ctx` intentionally.
Since the "environment" should be more flexible than having to have a `ctx`.

[1]: aa32940279

Reviewed By: mitrandir77

Differential Revision: D8221079

fbshipit-source-id: 94ee5c563f943330ef91966a4883c5733cc8dac9
This commit is contained in:
Jun Wu 2018-06-06 15:21:27 -07:00 committed by Facebook Github Bot
parent bdbcbf962b
commit 1499191e20
2 changed files with 21 additions and 0 deletions

View File

@ -966,6 +966,26 @@ def isstdiofilename(pat):
return not pat or pat == "-"
def rendertemplate(ui, tmpl, props=None):
"""Render tmpl written in the template language. props provides the
"environment" which the template program runs in.
Return the rendered string.
>>> import mercurial.ui as uimod
>>> rendertemplate(uimod.ui(), '{a} {b|json}', {'a': 'x', 'b': [3, None]})
'x [3, null]'
"""
t = formatter.maketemplater(ui, tmpl, cache=templatekw.defaulttempl)
mapping = {"ui": ui, "templ": t}
if props:
if "ctx" in props:
mapping["revcache"] = {}
mapping.update(props)
mapping.update(templatekw.keywords)
return t.render(mapping)
class _unclosablefile(object):
def __init__(self, fp):
self._fp = fp

View File

@ -49,6 +49,7 @@ def testmod(name, optionflags=0, testtarget=None):
testmod("mercurial.changegroup")
testmod("mercurial.changelog")
testmod("mercurial.cmdutil")
testmod("mercurial.color")
testmod("mercurial.config")
testmod("mercurial.context")