Skip to content

Conversation

@cossssmin
Copy link
Member

@cossssmin cossssmin commented Mar 20, 2020

Proposed Changes

This PR adds functionality that exposes some information about the loop currently being executed.

A loop object is constructed and passed into the locals of the loop being executed.

Inside a loop, you now have access to the following variables:

  • loop.index - the current iteration of the loop (0 indexed)
  • loop.remaining - number of iterations until the end (0 indexed)
  • loop.first - boolean indicating if it's the first iteration
  • loop.last - boolean indicating if it's the last iteration
  • loop.length - total number of items

Usage

<each loop='item in items'>
  <li>Item value: {{ item }}</li>
  <li>Current iteration of the loop: {{ loop.index }}</li>
  <li>Number of iterations until the end: {{ loop.remaining }}</li>
  <li>This {{ loop.first ? 'is' : 'is not' }} the first iteration</li>
  <li>This {{ loop.last ? 'is' : 'is not' }} the last iteration</li>
  <li>Total number of items: {{ loop.length }}</li>
</each>

Nested loops

The loop object contains information about the current loop.

This means you can't access the loop.remaining variable of the parent loop.

A possible solution, though outside the scope of this PR, would be for the <each> tag to accept a locals="" attribute, which could be used to pass down data - in this case, the parent loop's metadata.

Types of Changes

  • Bug (non-breaking change which fixes an issue)
  • Feature (non-breaking change which adds functionality)
  • Breaking Change (fix or feature which changes existing functionality)

Checklist

  • I have read the CONTRIBUTING guide
  • Lint and unit tests pass with my changes
  • I have added tests that prove my fix is effective/works
  • I have added necessary documentation (if appropriate)
  • Any dependent changes are merged and published in downstream modules

If merged, this PR closes #65

@coveralls
Copy link

coveralls commented Mar 20, 2020

Coverage Status

Coverage increased (+0.07%) to 97.423% when pulling 3cff5cb on cossssmin:loop-meta into e99bb12 on posthtml:master.

@cossssmin
Copy link
Member Author

Extracted to a getLoopMeta function where I check what we're iterating over and compute the object with loop metadata accordingly. Please check and let me know what you think.

@cossssmin
Copy link
Member Author

Forgot to add docs, doing it now!

@Scrum Scrum merged commit bcdb13a into posthtml:master Mar 23, 2020
@Scrum
Copy link
Member

Scrum commented Mar 23, 2020

publish v1.3.0

@cossssmin cossssmin deleted the loop-meta branch May 7, 2020 08:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] Loop-related variables

4 participants