Context Variables
When iterating over an array (with:map, :every, :some, :find, or :filter), penscript makes the following context variables available inside the loop body:
| Variable | Description |
|---|---|
{@item} | The current item value |
{@index} | Current index (0, 1, 2…) |
{@position} | Current position (1, 2, 3…) |
{@first} | true if the current item is the first |
{@last} | true if the current item is the last |
{@item.name}, {@item.role}, {@item.amount}.
Normalizing to Arrays: :array
Wraps a value in an array if it isn’t one already. Useful for ensuring consistent array input when a value might be a single item or an array.
Generating Arrays with :fill
Combine :array with :fill to generate arrays of a specific length. Each element is created from the :fill template, with context variables available.
Mapping: :map
Transforms every item in an array. The transformation expression has access to {@item}, {@index}, {@position}, {@first}, and {@last}.
Using :to syntax:
:with:
This is the most powerful pattern — generating dynamic structures from data. The :with operator creates local variables for each iteration, keeping the template readable.
Filtering: :filter
Removes items from an array based on a condition. Works by mapping items to themselves (kept) or false (removed), then stripping the falsy values.
Finding Items: :find
Returns the first item in an array that matches a condition. If no match is found, returns undefined.
Membership & Intersections
:includes
Tests if an array contains a specific value.
:if for access control patterns:
:intersects
Tests if two arrays share any common elements.
Counting: :count
Returns the number of items in an array.
Conditional Counting with :where
Count only items that satisfy a condition:
Excluding Items with :unless
Combine :where and :unless for fine-grained filtering:
Range Arrays: :range-array
Generates an array of sequential integers. The start is inclusive, the end is exclusive.
:map to generate a dynamic number of form fields or UI elements based on a user-provided count.
Flattening: :flatten
Deeply flattens nested arrays into a single flat array.
:map that produces arrays of arrays — for example, when each mapped item generates multiple form fields and you need them in a single flat list.
Sequence Check: :increasing
Returns true if all values in the array are in strictly increasing order.