Skip to content

Instantly share code, notes, and snippets.

@groue
Created September 22, 2012 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groue/3765850 to your computer and use it in GitHub Desktop.
Save groue/3765850 to your computer and use it in GitHub Desktop.
GRMustache: objects that render themselves
{{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 {
Person *orsonWelles = [Person personWithFirstName:@"Orson" lastName:@"Welles"];
Movie *movie = [Movie movieWithTitle:@"Citizen Kane" director:orsonWelles];
id data = @{ @"movie": movie };
NSString *rendering = [GRMustacheTemplate renderObject:data
fromResource:@"Document"
bundle:nil
error:NULL];
}
}
Citizen Kane by Orson Welles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment