posthtml / posthtml-expressions

Use variables, JS-like expressions, and even markup-powered logic in your HTML.
Other
123 stars 20 forks source link

Add loop metadata. #66

Closed cossssmin closed 4 years ago

cossssmin commented 4 years ago

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:

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

Checklist


If merged, this PR closes #65

coveralls commented 4 years ago

Coverage Status

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

cossssmin commented 4 years ago

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 commented 4 years ago

Forgot to add docs, doing it now!

Scrum commented 4 years ago

publish v1.3.0