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

Added support for @first and @last in each. #6

Merged
merged 1 commit into from
Aug 15, 2014
Merged
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
17 changes: 15 additions & 2 deletions pybars/_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,13 @@ def escape(something, _escape_re=_escape_re, substitute=substitute):

class Scope:

def __init__(self, context, parent, index=None, key=None):
def __init__(self, context, parent, index=None, key=None, first=None, last=None):
self.context = context
self.parent = parent
self.index = index
self.key = key
self.first = first
self.last = last

def get(self, name, default=None):
if name == '__parent':
Expand All @@ -191,6 +193,10 @@ def get(self, name, default=None):
return self.index
if name == '@key' and self.key is not None:
return self.key
if name == '@first' and self.first is not None:
return self.first
if name == '@last' and self.last is not None:
return self.last
if name == 'this':
return self.context
result = self.context.get(name, self)
Expand Down Expand Up @@ -225,12 +231,19 @@ def resolve(context, *segments):
def _each(this, options, context):
result = strlist()
i = 0
if isinstance(context, list) or isinstance(context, dict):
context_length = len(context)
else:
context_length = None
for local_context in context:
kwargs = {}
if isinstance(context, list):
kwargs['index'] = i
if isinstance(context, dict):
elif isinstance(context, dict):
kwargs['key'] = local_context
kwargs['first'] = (i==0)
if context_length is not None:
kwargs['last'] = (i==(context_length-1))
scope = Scope(local_context, this, **kwargs)
result.grow(options['fn'](scope))
i += 1
Expand Down