fix(variable): Prevent crash on unknown index in array

This commit is contained in:
Kyle Fuller
2016-10-13 13:11:02 +01:00
parent 72f3cb579a
commit 1e3afc0dd5
3 changed files with 29 additions and 1 deletions

View File

@@ -1,4 +1,14 @@
# Stencil Changelog # Stencil Changelog
## Master
### Bug Fixes
- Variables (`{{ variable.5 }}`) that reference an array index at an unknown
index will now resolve to `nil` instead of causing a crash.
[#72](https://github.com/kylef/Stencil/issues/72)
## 0.6.0 ## 0.6.0
### Enhancements ### Enhancements

View File

@@ -64,7 +64,11 @@ public struct Variable : Equatable, Resolvable {
current = dictionary[bit] current = dictionary[bit]
} else if let array = current as? [Any] { } else if let array = current as? [Any] {
if let index = Int(bit) { if let index = Int(bit) {
current = array[index] if index >= 0 && index < array.count {
current = array[index]
} else {
current = nil
}
} else if bit == "first" { } else if bit == "first" {
current = array.first current = array.first
} else if bit == "last" { } else if bit == "last" {

View File

@@ -52,6 +52,20 @@ func testVariable() {
let variable = Variable("contacts.0") let variable = Variable("contacts.0")
let result = try variable.resolve(context) as? String let result = try variable.resolve(context) as? String
try expect(result) == "Katie" try expect(result) == "Katie"
let variable1 = Variable("contacts.1")
let result1 = try variable1.resolve(context) as? String
try expect(result1) == "Carlton"
}
$0.it("can resolve an item from an array via unknown index") {
let variable = Variable("contacts.5")
let result = try variable.resolve(context) as? String
try expect(result).to.beNil()
let variable1 = Variable("contacts.-5")
let result1 = try variable1.resolve(context) as? String
try expect(result1).to.beNil()
} }
$0.it("can resolve the first item from an array") { $0.it("can resolve the first item from an array") {