Skip to content

Instantly share code, notes, and snippets.

@popcornylu
Created December 23, 2011 07:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save popcornylu/1513528 to your computer and use it in GitHub Desktop.
Save popcornylu/1513528 to your computer and use it in GitHub Desktop.
A very simple template engine for iOS
#import "NSString+template.h"
@implementation NSString (template)
+(NSString*)stringWithTemplate:(NSString*)template
fromMap:(NSDictionary*)map
{
NSString* retStr = nil;
NSMutableString* buffer = [NSMutableString new];
NSScanner* scanner = [[NSScanner alloc] initWithString:template];
NSString* tempString = nil;
while([scanner scanUpToString:@"$[" intoString:&tempString])
{
NSString* key = nil;
NSString* value = nil;
[buffer appendString:tempString];
if([scanner isAtEnd])
{
break;
}
[scanner scanString:@"$[" intoString:nil];
[scanner scanUpToString:@"]" intoString:&key];
[scanner scanString:@"]" intoString:nil];
if(key)
{
value = [map objectForKey:key];
}
if(value)
{
[buffer appendString:value];
}
else
{
[buffer appendFormat:@"$[%@]", key];
}
}
retStr = [NSString stringWithString:buffer];
[buffer release];
[scanner release];
return retStr;
}
@end
#import <Foundation/Foundation.h>
@interface NSString (template)
+(NSString*)stringWithTemplate:(NSString*)template
fromMap:(NSDictionary*)map;
@end
- (void)test
{
NSString* testTemplate = @"Hello $[name], welcome to $[city].";
NSString* testString =
[NSString stringWithTemplate:testTemplate
fromMap:[NSDictionary dictionaryWithObjectsAndKeys:
@"Popcorny", @"name"
@"Taipei", @"city",
nil]];
NSLog(@"%@", testString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment