Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding the ability to select list items in the context by index. #143

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion pystache/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,17 @@ def _get_value(context, key):
# (e.g. catching KeyError).
if key in context:
return context[key]
elif type(context).__module__ != _BUILTIN_MODULE:
if isinstance(context, list):
# If we're dealing with a list or a list subclass attempt to use the key
# as an index on the list.
#
# We pass on ValueError (the key is not an int) or IndexError (the key/int
# is not in the list). And continue with normal processing.
try:
return context[int(key)]
except (ValueError, IndexError):
pass
if type(context).__module__ != _BUILTIN_MODULE:
# Then we consider the argument an "object" for the purposes of
# the spec.
#
Expand Down
15 changes: 15 additions & 0 deletions pystache/tests/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,12 @@ class MyList(list): pass
self.assertEqual(_get_value(item1, 'pop'), 2)
self.assertNotFound(item2, 'pop')

# get list items by index
self.assertEqual(_get_value(item2, '0'), 1)

# Don't throw errors if we pass a non-int to a list.
self.assertNotFound(item2, 'numberone')


class ContextStackTestCase(unittest.TestCase, AssertIsMixin, AssertStringMixin,
AssertExceptionMixin):
Expand Down Expand Up @@ -497,3 +503,12 @@ def bar(self):

stack = ContextStack({"foo": Foo()})
self.assertEqual(stack.get(name), "Baz")

def test_dot_notation__list(self):
""" Test that an index interger after a dot correctly grabs the item
if the parent is a list.

"""
name = "foo.1"
stack = ContextStack({"foo": ['Ignore me.', 'Choose me!']})
self.assertEqual(stack.get(name), "Choose me!")