Created
December 23, 2011 07:59
-
-
Save popcornylu/1513528 to your computer and use it in GitHub Desktop.
A very simple template engine for iOS
This file contains 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 "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 |
This file contains 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 <Foundation/Foundation.h> | |
@interface NSString (template) | |
+(NSString*)stringWithTemplate:(NSString*)template | |
fromMap:(NSDictionary*)map; | |
@end |
This file contains 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
- (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