Added sections tests. Allow for searching of context stack

This commit is contained in:
Adam Fowler
2021-03-18 10:32:42 +00:00
parent b07ad42b49
commit 16a2c54be6
4 changed files with 303 additions and 30 deletions

View File

@@ -2,37 +2,45 @@
/// Protocol for objects that can be rendered as a sequence in Mustache
public protocol HBMustacheSequence {
/// Render section using template
func renderSection(with template: HBMustacheTemplate) -> String
func renderSection(with template: HBMustacheTemplate, stack: [Any]) -> String
/// Render inverted section using template
func renderInvertedSection(with template: HBMustacheTemplate) -> String
func renderInvertedSection(with template: HBMustacheTemplate, stack: [Any]) -> String
}
public extension Sequence {
/// Render section using template
func renderSection(with template: HBMustacheTemplate) -> String {
func renderSection(with template: HBMustacheTemplate, stack: [Any]) -> String {
var string = ""
var context = HBMustacheContext(first: true)
var iterator = makeIterator()
guard var currentObject = iterator.next() else { return "" }
while let object = iterator.next() {
string += template.render(currentObject, context: context)
var stack = stack
stack.append(currentObject)
string += template.render(stack, context: context)
currentObject = object
context.first = false
context.index += 1
}
context.last = true
string += template.render(currentObject, context: context)
var stack = stack
stack.append(currentObject)
string += template.render(stack, context: context)
return string
}
/// Render inverted section using template
func renderInvertedSection(with template: HBMustacheTemplate) -> String {
func renderInvertedSection(with template: HBMustacheTemplate, stack: [Any]) -> String {
var stack = stack
stack.append(self)
var iterator = makeIterator()
if iterator.next() == nil {
return template.render(self)
return template.render(stack)
}
return ""
}