Commit 01dd06b3 by Carl Whittaker

Adding support for callables and Negated values.

parent b7ab439a
...@@ -18,3 +18,6 @@ class ComplexView(pystache.View): ...@@ -18,3 +18,6 @@ class ComplexView(pystache.View):
def empty(self): def empty(self):
return len(self.item()) == 0 return len(self.item()) == 0
def empty_list(self):
return [];
...@@ -61,13 +61,20 @@ class Template(object): ...@@ -61,13 +61,20 @@ class Template(object):
it = view.get(section_name, None) it = view.get(section_name, None)
replacer = '' replacer = ''
# Callable
if it and isinstance(it, collections.Callable):
replacer = it(inner)
# Dictionary # Dictionary
if it and hasattr(it, 'keys') and hasattr(it, '__getitem__'): elif it and hasattr(it, 'keys') and hasattr(it, '__getitem__'):
if section[2] != '^': if section[2] != '^':
replacer = self._render_dictionary(inner, it) replacer = self._render_dictionary(inner, it)
# Lists
elif it and hasattr(it, '__iter__'): elif it and hasattr(it, '__iter__'):
if section[2] != '^': if section[2] != '^':
replacer = self._render_list(inner, it) replacer = self._render_list(inner, it)
# Falsey and Negated or Truthy and Not Negated
elif (not it and section[2] == '^') or (it and section[2] != '^'):
replacer = inner
template = template.replace(section, replacer) template = template.replace(section, replacer)
......
import unittest import unittest
import pystache import pystache
from examples.nested_context import NestedContext
from examples.complex_view import ComplexView
from examples.lambdas import Lambdas
class TestSimple(unittest.TestCase): class TestSimple(unittest.TestCase):
...@@ -7,3 +10,19 @@ class TestSimple(unittest.TestCase): ...@@ -7,3 +10,19 @@ class TestSimple(unittest.TestCase):
tmpl = '{{derp}}' tmpl = '{{derp}}'
self.assertEqual('herp', pystache.Template(tmpl, {'derp': 'herp'}).render()) self.assertEqual('herp', pystache.Template(tmpl, {'derp': 'herp'}).render())
def test_nested_context(self):
view = NestedContext()
self.assertEquals(pystache.Template('{{#foo}}{{thing1}} and {{thing2}} and {{outer_thing}}{{/foo}}{{^foo}}Not foo!{{/foo}}', view).render(), "one and foo and two")
def test_looping_and_negation_context(self):
view = ComplexView()
self.assertEquals(pystache.Template('{{#item}}{{header}}: {{name}} {{/item}}{{^item}} Shouldnt see me{{/item}}', view).render(), "Colors: red Colors: green Colors: blue ")
def test_empty_context(self):
view = ComplexView()
self.assertEquals(pystache.Template('{{#empty_list}}Shouldnt see me {{/empty_list}}{{^empty_list}}Should see me{{/empty_list}}', view).render(), "Should see me")
def test_callables(self):
view = Lambdas()
self.assertEquals(pystache.Template('{{#replace_foo_with_bar}}foo != bar. oh, it does!{{/replace_foo_with_bar}}', view).render(), 'bar != bar. oh, it does!')
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment