fix(variable): Prevent crash on unknown index in array
This commit is contained in:
10
CHANGELOG.md
10
CHANGELOG.md
@@ -1,4 +1,14 @@
|
||||
# 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
|
||||
|
||||
### Enhancements
|
||||
|
||||
@@ -64,7 +64,11 @@ public struct Variable : Equatable, Resolvable {
|
||||
current = dictionary[bit]
|
||||
} else if let array = current as? [Any] {
|
||||
if let index = Int(bit) {
|
||||
current = array[index]
|
||||
if index >= 0 && index < array.count {
|
||||
current = array[index]
|
||||
} else {
|
||||
current = nil
|
||||
}
|
||||
} else if bit == "first" {
|
||||
current = array.first
|
||||
} else if bit == "last" {
|
||||
|
||||
@@ -52,6 +52,20 @@ func testVariable() {
|
||||
let variable = Variable("contacts.0")
|
||||
let result = try variable.resolve(context) as? String
|
||||
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") {
|
||||
|
||||
Reference in New Issue
Block a user