Template inheritance (#9)
* Move all context variables into HBMustacheContext * Add support for reading inherited sections * Render inherited tokens * Test inheritance spec, fix two minor issues * fix warning * swift format
This commit is contained in:
@@ -1,46 +1,39 @@
|
||||
|
||||
/// Protocol for objects that can be rendered as a sequence in Mustache
|
||||
public protocol HBMustacheSequence {
|
||||
protocol HBMustacheSequence {
|
||||
/// Render section using template
|
||||
func renderSection(with template: HBMustacheTemplate, stack: [Any]) -> String
|
||||
func renderSection(with template: HBMustacheTemplate, context: HBMustacheContext) -> String
|
||||
/// Render inverted section using template
|
||||
func renderInvertedSection(with template: HBMustacheTemplate, stack: [Any]) -> String
|
||||
func renderInvertedSection(with template: HBMustacheTemplate, context: HBMustacheContext) -> String
|
||||
}
|
||||
|
||||
public extension Sequence {
|
||||
extension Sequence {
|
||||
/// Render section using template
|
||||
func renderSection(with template: HBMustacheTemplate, stack: [Any]) -> String {
|
||||
func renderSection(with template: HBMustacheTemplate, context: HBMustacheContext) -> String {
|
||||
var string = ""
|
||||
var context = HBMustacheSequenceContext(first: true)
|
||||
var sequenceContext = HBMustacheSequenceContext(first: true)
|
||||
|
||||
var iterator = makeIterator()
|
||||
guard var currentObject = iterator.next() else { return "" }
|
||||
|
||||
while let object = iterator.next() {
|
||||
var stack = stack
|
||||
stack.append(currentObject)
|
||||
string += template.render(stack, context: context)
|
||||
string += template.render(context: context.withSequence(currentObject, sequenceContext: sequenceContext))
|
||||
currentObject = object
|
||||
context.first = false
|
||||
context.index += 1
|
||||
sequenceContext.first = false
|
||||
sequenceContext.index += 1
|
||||
}
|
||||
|
||||
context.last = true
|
||||
var stack = stack
|
||||
stack.append(currentObject)
|
||||
string += template.render(stack, context: context)
|
||||
sequenceContext.last = true
|
||||
string += template.render(context: context.withSequence(currentObject, sequenceContext: sequenceContext))
|
||||
|
||||
return string
|
||||
}
|
||||
|
||||
/// Render inverted section using template
|
||||
func renderInvertedSection(with template: HBMustacheTemplate, stack: [Any]) -> String {
|
||||
var stack = stack
|
||||
stack.append(self)
|
||||
|
||||
func renderInvertedSection(with template: HBMustacheTemplate, context: HBMustacheContext) -> String {
|
||||
var iterator = makeIterator()
|
||||
if iterator.next() == nil {
|
||||
return template.render(stack)
|
||||
return template.render(context: context.withObject(self))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user