Skip to content

Instantly share code, notes, and snippets.

@groue
Created September 27, 2012 07:55
Show Gist options
  • Save groue/3792756 to your computer and use it in GitHub Desktop.
Save groue/3792756 to your computer and use it in GitHub Desktop.
GRMustache: use dynamic partials to render a collection of objects
{{movies}} {{! one movie is not enough }}
{{title}} by {{director}}
{{firstName}} {{lastName}}
#import "GRMustache.h"
#import "Movie.h"
#import "Person.h"
// Declare categories on our classes so that they conform to the
// GRMustacheRendering protocol:
@interface Movie(GRMustache)<GRMustacheRendering>
@end
@interface Person(GRMustache)<GRMustacheRendering>
@end
// Now implement the protocol:
@implementation Movie(GRMustache)
- (NSString *)renderForMustacheTag:(GRMustacheTag *)tag context:(GRMustacheContext *)context HTMLSafe:(BOOL *)HTMLSafe error:(NSError **)error
{
// Extract the "Movie.mustache" partial from the original templateRepository:
GRMustacheTemplate *partial = [tag.templateRepository templateNamed:@"Movie" error:NULL];
// Add self to the top of the context stack, so that the partial
// can access our keys:
context = [context contextByAddingObject:self];
// Return the rendering of the partial
return [partial renderContentWithContext:context HTMLSafe:HTMLSafe error:error];
}
@end
@implementation Person(GRMustache)
- (NSString *)renderForMustacheTag:(GRMustacheTag *)tag context:(GRMustacheContext *)context HTMLSafe:(BOOL *)HTMLSafe error:(NSError **)error
{
// Extract the "Person.mustache" partial from the original templateRepository:
GRMustacheTemplate *partial = [tag.templateRepository templateNamed:@"Person" error:NULL];
// Add self to the top of the context stack, so that the partial
// can access our keys:
context = [context contextByAddingObject:self];
// Return the rendering of the partial
return [partial renderContentWithContext:context HTMLSafe:HTMLSafe error:error];
}
@end
// Render
main() {
@autoreleasepool {
id data = @{
@"movies": @[
[Movie movieWithTitle:@"Citizen Kane"
director:[Person personWithFirstName:@"Orson" lastName:@"Welles"]],
[Movie movieWithTitle:@"Some Like It Hot"
director:[Person personWithFirstName:@"Billy" lastName:@"Wilder"]],
]
};
NSString *rendering = [GRMustacheTemplate renderObject:data
fromResource:@"Document"
bundle:nil
error:NULL];
}
}
Citizen Kane by Orson Welles
Some Like It Hot by Billy Wilder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment