Skip to content

Instantly share code, notes, and snippets.

@groue
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save groue/401e88b7148bc126adb3 to your computer and use it in GitHub Desktop.

Select an option

Save groue/401e88b7148bc126adb3 to your computer and use it in GitHub Desktop.
GRMustache.swift cycle
import Mustache
// Wrap the result in a section, and the key `cycleKey` will enumerate and cycle
// around boxes, one after the other.
func cyclingBox(key cycleKey: String, #boxes: [MustacheBox]) -> MustacheBox {
var index = 0
return Box { (key: String) in
if key == cycleKey {
let box = boxes[index]
index = (index + 1) % boxes.count
return box
} else {
return Box()
}
}
}
let templateString =
"First cycle:\n" +
"{{#cycle}}" +
"{{x}}{{x}}{{x}}{{x}}{{x}}" +
"{{/cycle}}" +
"\nNext cycle:\n" +
"{{#cycle}}" +
"{{x}}{{x}}{{x}}{{x}}{{x}}" +
"{{/cycle}}" +
"\nCycle wrapped in another cycle:\n" +
"{{#cycle}}" +
"{{x}}{{x}}" +
"(" +
"{{#cycle}}" +
"{{x}}{{x}}{{x}}{{x}}" +
"{{/cycle}}" +
")" +
"{{x}}{{x}}" +
"{{/cycle}}"
let template = Template(string: templateString)!
// Rendering:
//
// First cycle:
// ABCAB
// Next cycle:
// ABCAB
// Cycle wrapped in another cycle:
// AB(ABCA)CA
let cycle = cyclingBox(key: "x", boxes: [Box("A"), Box("B"), Box("C")])
let rendering = template.render(Box(["cycle": cycle]))!
print(rendering)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment