Files
swiftpm-stencil/Stencil/Context.swift
2015-10-22 11:42:50 -07:00

46 lines
1.1 KiB
Swift

/// A container for template variables.
public class Context {
var dictionaries:[[String: Any]]
/// Initialise a Context with a dictionary
public init(dictionary:[String: Any]) {
dictionaries = [dictionary]
}
/// Initialise an empty Context
public init() {
dictionaries = []
}
public subscript(key: String) -> Any? {
/// Retrieves a variable's value, starting at the current context and going upwards
get {
for dictionary in Array(dictionaries.reverse()) {
if let value = dictionary[key] {
return value
}
}
return nil
}
/// Set a variable in the current context, deleting the variable if it's nil
set(value) {
if var dictionary = dictionaries.popLast() {
dictionary[key] = value
dictionaries.append(dictionary)
}
}
}
/// Push a new level into the Context
public func push(dictionary: [String: Any]? = nil) {
dictionaries.append(dictionary ?? [:])
}
/// Pop the last level off of the Context
public func pop() -> [String: Any]? {
return dictionaries.popLast()
}
}