Skip to content

Commit

Permalink
[for block] Handle empty nodes
Browse files Browse the repository at this point in the history
Closes #35
  • Loading branch information
kylef committed Oct 26, 2015
1 parent 9b26b7d commit 507cc5c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 16 deletions.
18 changes: 10 additions & 8 deletions Stencil/Node.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ public class ForNode : NodeType {
let variable:Variable
let loopVariable:String
let nodes:[NodeType]
let emptyNodes: [NodeType]

public class func parse(parser:TokenParser, token:Token) throws -> NodeType {
let components = token.components()
Expand Down Expand Up @@ -150,22 +151,23 @@ public class ForNode : NodeType {
self.variable = Variable(variable)
self.loopVariable = loopVariable
self.nodes = nodes
// TODO: Handle emptyNodes
self.emptyNodes = emptyNodes
}

public func render(context: Context) throws -> String {
let values = try variable.resolve(context)
if let values = values as? NSArray {

if let values = values as? NSArray where values.count > 0 {
return try values.map { item in
context.push()
context[loopVariable] = item
let result = try renderNodes(nodes, context)
context.pop()
return result
try context.push([loopVariable: item]) {
try renderNodes(nodes, context)
}
}.joinWithSeparator("")
}

return ""
return try context.push {
try renderNodes(emptyNodes, context)
}
}
}

Expand Down
23 changes: 23 additions & 0 deletions StencilSpecs/Nodes/ForNodeSpec.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import Spectre
import Stencil


describe("ForNode") {
let context = Context(dictionary: [
"items": [1, 2, 3],
"emptyItems": [Int](),
])

$0.it("renders the given nodes for each item") {
let nodes: [NodeType] = [VariableNode(variable: "item")]
let node = ForNode(variable: "items", loopVariable: "item", nodes: nodes, emptyNodes: [])
try expect(try node.render(context)) == "123"
}

$0.it("renders the given empty nodes when no items found item") {
let nodes: [NodeType] = [VariableNode(variable: "item")]
let emptyNodes: [NodeType] = [TextNode(text: "empty")]
let node = ForNode(variable: "emptyItems", loopVariable: "item", nodes: nodes, emptyNodes: emptyNodes)
try expect(try node.render(context)) == "empty"
}
}
8 changes: 0 additions & 8 deletions StencilSpecs/Nodes/NodeSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,4 @@ describe("Node") {
try expect(try renderNodes(nodes, context)).toThrow(TemplateSyntaxError("Custom Error"))
}
}

$0.describe("ForNode") {
$0.it("renders the given nodes for each item") {
let nodes: [NodeType] = [VariableNode(variable: "item")]
let node = ForNode(variable: "items", loopVariable: "item", nodes: nodes, emptyNodes: [])
try expect(try node.render(context)) == "123"
}
}
}

0 comments on commit 507cc5c

Please sign in to comment.