2011年12月23日 星期五

Simple template engine for objective c

所謂template engine就是我們可以先定義一個template
例如一個html檔案
然後我們會希望把裡面少部分的片段透過程式去取代成我們想要的字串
而做這些取代動作的東西我們就稱作template engine

其實在iOS當中已經有一個非常簡單的template engine了,
也就是+[NSString stringWithFormat:(NSString *)format, …]
這東西就很像在c使用sprintf(...)
然而,這東西對大部份來時候來講都很好用,但是也有一些限制,
例如它必需要要一個蘿蔔一個坑 (傳進的參數就是對應到format中的每個%開頭的取代標示)
你不能要求一個蘿蔔兩個坑 (一個參數取代兩個取代標示)
甚至第一個蘿蔔一定要放在第一個坑 (第一個參數一定要放在第一個取代標示)

我查了一下stackoverflow
但是沒有找到我想要的答案
http://stackoverflow.com/questions/2539556/objectivec-builtin-template-system
得到的答案不外乎就是這幾個
1. 用上面提的+[NSString stringWithFormat:(NSString *)format, …]
2. 用-[NSString stringByReplacingOccurrencesOfString:withString:]
然後一個一個把取代標示換成我們要的字串
3. 不然就是給我一個非常強大的template engine..

其實這東西不難做,既然我們都已經有好用的NSScanner了,那我們就做一個簡單的template engine吧。
使用上我希望長這樣
NSString* testTemplate = @"Hello $[name], welcome to $[city].";

NSString* testString =
    [NSString stringWithTemplate:testTemplate
                         fromMap:[NSDictionary dictionaryWithObjectsAndKeys:
                                  @"Popcorny", @"name"
                                  @"Taipei", @"city",
                                  nil]];
NSLog(@"%@", testString);   // output: Hello Popcorny, welcome to Taipei."


程式碼如下