Skip to content

Commit

Permalink
Merge a1f0424 into 4bc5648
Browse files Browse the repository at this point in the history
  • Loading branch information
ergoithz committed Jan 2, 2021
2 parents 4bc5648 + a1f0424 commit ee9f4f3
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 2 deletions.
58 changes: 56 additions & 2 deletions chevron/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,60 @@ def _get_partial(name, partials_dict, partials_path, partials_ext):
return ''


#
# Render class
#
class RenderFunction(object):
"""Callable section render function."""

__slots__ = ('_kwargs', '_scopes')

def __init__(self, scopes, **kwargs):
"""Initialize with scope and render kwargs.
Arguments:
scopes -- The list of scopes that get_key will look through
**kwargs -- Keyword arguments forwarded to render
"""
self._scopes = scopes
self._kwargs = kwargs

def get(self, key):
"""Get a key from the current scope.
Arguments:
key -- Key to look in current data scope
Returns:
Value from data scope, or empty string if not found.
"""
return _get_key(key, self._scopes)

def __call__(self, template, data=None):
"""Render template on current scope.
Arguments:
template -- A file-like object or a string containing the
template
data -- A python dictionary with your data scope
Returns:
A string containing the rendered template.
"""
return render(
template,
scopes=data and [data] + self._scopes or self._scopes,
**self._kwargs
)


#
# The main rendering function
#
Expand Down Expand Up @@ -281,14 +335,14 @@ def render(template='', data={}, partials_path='.', partials_ext='mustache',

g_token_cache[text] = tags

rend = scope(text, lambda template, data=None: render(template,
rend = scope(text, RenderFunction(
data={},
partials_path=partials_path,
partials_ext=partials_ext,
partials_dict=partials_dict,
padding=padding,
def_ldel=def_ldel, def_rdel=def_rdel,
scopes=data and [data]+scopes or scopes))
scopes=scopes))

if python3:
output += rend
Expand Down
28 changes: 28 additions & 0 deletions test_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,34 @@ def function(content, render):

self.assertEqual(result, expected)

def test_callable_5(self):
'''Test render with function accessing current context
'''

def keys(content, render):
result = []
mapping = render.get('.')
if mapping:
for key in sorted(mapping):
result.append(render(content, key))
return ''.join(result)

args = {
'template': '{{#dct}}{{#keys}}{{.}}{{/keys}}{{/dct}}',
'data': {
'keys': keys,
'dct': {
'ka': 'va',
'kb': 'kb',
}
}
}

result = chevron.render(**args)
expected = 'kakb'

self.assertEqual(result, expected)

# https://github.com/noahmorrison/chevron/issues/35
def test_custom_falsy(self):
class CustomData(dict):
Expand Down

0 comments on commit ee9f4f3

Please sign in to comment.