noahmorrison / chevron

A Python implementation of mustache
MIT License
486 stars 52 forks source link

Fix the rendering of lambdas #43

Closed akosthekiss closed 5 years ago

akosthekiss commented 5 years ago

Variables are the most common tag types, yet they were not handled during the generation of template text for lambda scopes.

coveralls commented 5 years ago

Coverage Status

Coverage remained the same at ?% when pulling 24b7f302ee2060b6590fdc0ed1be2b0a45e55d6f on akosthekiss:fix-lambda-variable into 8abcc371f507239c3374300e6d5cd1365aca7893 on noahmorrison:master.

akosthekiss commented 5 years ago

Right now, the lambda example in the README runs into an error. To track down the issue, I've created a smaller test case. Both listed below:

My test case:

import chevron

def hello(text, render):
    return 'Hello ' +  render(text) + '!'

args = {
    'template': '{{#hello}}{{x}}{{/hello}}',
    'data': { 'x': 'World', 'hello': hello }
}

chevron.render(**args)

README lambda example:

import chevron

def first(text, render):
    # return only first occurance of items
    result = render(text)
    return [ x.strip() for x in result.split(" || ") if x.strip() ][0]

def inject_x(text, render):
    # inject data into scope
    return render(text, {'x': 'data'})

args = {
    'template': 'Hello, {{# first}} {{x}} || {{y}} || {{z}} {{/ first}}!  {{# inject_x}} {{x}} {{/ inject_x}}',

    'data': {
        'y': 'foo',
        'z': 'bar',
        'first': first,
        'inject_x': inject_x
    }
}

chevron.render(**args)

Both snippets fail with the following diagnostics:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "chevron/renderer.py", line 253, in render
    }[tag_type], tag_key, def_rdel)
KeyError: 'variable'

With the here-proposed patch, I get the following (correct, I think) output:

'Hello World!'
'Hello, foo!   data '
akosthekiss commented 5 years ago

PR rebased to latest master to make Travis CI go green.