Last active
August 29, 2015 14:15
-
-
Save groue/401e88b7148bc126adb3 to your computer and use it in GitHub Desktop.
GRMustache.swift cycle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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