Skip to content

Commit acd06dc

Browse files
author
Jeff Escalante
committed
object loop
1 parent 9ed7be3 commit acd06dc

File tree

4 files changed

+35
-4
lines changed

4 files changed

+35
-4
lines changed

lib/index.js

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,10 +142,10 @@ function walk (opts, nodes) {
142142

143143
if (Array.isArray(target)) {
144144
for (let index = 0; index < target.length; index++) {
145-
const item = target[index]
146-
// add item and optional index loop locals
145+
const value = target[index]
146+
// add value and optional index loop locals
147147
const scopedLocals = {}
148-
scopedLocals[loopParams.keys[0]] = item
148+
scopedLocals[loopParams.keys[0]] = value
149149
if (loopParams.keys[1]) scopedLocals[loopParams.keys[1]] = index
150150
// merge nondestructively into existing locals
151151
const scopedOptions = merge(opts, { locals: scopedLocals })
@@ -158,7 +158,22 @@ function walk (opts, nodes) {
158158
}
159159
return m
160160
} else {
161-
// object loop
161+
for (let key in target) {
162+
const value = target[key]
163+
// add item and optional index loop locals
164+
const scopedLocals = {}
165+
scopedLocals[loopParams.keys[0]] = key
166+
if (loopParams.keys[1]) scopedLocals[loopParams.keys[1]] = value
167+
// merge nondestructively into existing locals
168+
const scopedOptions = merge(opts, { locals: scopedLocals })
169+
// provide the modified options to the content evaluation
170+
// we need to clone the node because the normal operation modifies
171+
// the node directly
172+
const content = cloneDeep(node.content)
173+
const res = walk(scopedOptions, content)
174+
m.push(res)
175+
}
176+
return m
162177
}
163178
}
164179

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<p>x</p>
2+
3+
<p>a: b</p>
4+
5+
<p>c: d</p>
6+
7+
<p>x</p>

test/fixtures/loop_object.html

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<p>x</p>
2+
<each loop='key, value in items'>
3+
<p>{{key}}: {{value}}</p>
4+
</each>
5+
<p>x</p>

test/index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ test('loop', (t) => {
7171
return matchExpected(t, 'loop', { locals: { items: [1, 2, 3] } })
7272
})
7373

74+
test('loop object', (t) => {
75+
return matchExpected(t, 'loop_object', { locals: { items: { a: 'b', c: 'd' } } })
76+
})
77+
7478
//
7579
// Utility
7680
//

0 commit comments

Comments
 (0)