iOS:使用模板引擎渲染HTML介面

來源:互聯網
上載者:User

標籤:實現   支援   代碼   測試   pat   meta   erro   ret   cti   

在實際開發中,UIWebView控制項接受一個HTML內容,用於相應的介面,下面是該API的介面:

- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL

由於HTML內容通常是變化的,所以我們需要在記憶體中產生該HTML內容。比較簡單粗暴的做法是將該HTML的基本內容定義在一個NSString中,然後用[NSString stringWothFormat]方法將內容進行格式化,樣本如下:

//給對應的標籤格式化內容-(NSString *)demoFormatWithName:(NSString *)name value:(NSString *)value{    NSString *html =    @"<!DOCTYPE html>\n"    "<html lang=\"zh-cn\">\n"    "<head>""\n"    "<meta charset=\"utf-8\">\n"    "<title>這是一個HTML測試</title>\n"    "</head>\n"    "<body>\n"    "<h1>%@</h1>\n"    "<p>%@</p>\n"    "<img src=\"http://img3.redocn.com/20131012/Redocn_2013101208320171.jpg\" width=\"256\" height=\"128\"><br><hr>\n"    "</body>\n"    "</html>";    NSString *content = [NSString stringWithFormat:html,name,value];    return content;}

但其實我們可以看出,這樣寫並不舒服,因為:

1、模板內容和代碼混在一起,既不方便閱讀,也不方便更改;

2、模板內容的渲染邏輯使用簡單的[NSString stringWothFormat]來完成,功能單一。在實際開發中,我們很可能需要就未經處理資料進行二次處理,而這些如果模板渲染模組不能支援,我們就只能自己手工鞋這部分資料二次處理,費時費力。例如,微博的詳情頁面,如果微博的發送時間小於1天,則需要顯示成"xxx小時前",如果小於1分鐘,則需要顯示成"剛剛"。這些介面渲染方便的邏輯如果能夠抽取到專門的排版代碼中,則會清晰很多。

所以我們需要一個模板引擎,專門負責這類渲染的工作。

模板引擎複雜的有:MGTemplateEngine(http://mattgemmell.com/mgtemplateengine-templates-with-cocoa/),它的範本語言比較像Smarty、FreeMarker和Django。另外它可以自由的定義Filter,以便實現上面提到的自訂渲染邏輯。它需要依賴RegexKit,RegexKit是一個Regex工具類,提供強大的運算式匹配和替換功能。

也有簡單的是:GRMustache(https://github.com/groue/GRMustache),它比MGTemplateEngine的功能更簡單。另外GRMustache在開源社區更加活躍、更新更加頻繁。

 

對於上面的範例程式碼,在使用GRMustache模板後,我們首先需要調整模板的內容:

1、將模板內容放在一個單獨的檔案中,方便日後更改,如template.html

2、將原來的%@替換成{{ name }}的形式。

例如調整後的模板內容為:(檔案名稱為:template.html) 

<!DOCTYPE html><html lang="zh-cn"><head>    <meta charset="utf-8">    <title>這是一個HTML測試</title></head><body>    <h1> {{ name }} </h1>    <p> {{ content }} </p>    <img src="http://img3.redocn.com/20131012/Redocn_2013101208320171.jpg" width="256" height="128"><br><hr></body></html>

即template.html

然後我們在代碼中將該檔案讀取到記憶體中,再使用GRMustache的renderObject方法產生渲染後的HTML內容,範例程式碼如下:

//給template.html中對應的標籤格式化內容-(NSString *)demoFormatWithName:(NSString *)name value:(NSString *)value{    NSString *fileName = @"template.html";    NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:fileName];    NSString *template = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];    NSDictionary *renderObject = @{@"name":name,@"content":value};    NSString *content = [GRMustacheTemplate renderObject:renderObject fromString:template error:nil];    return content;}

這樣,我們使用GRMustache模板引擎成功完成了HTML內容的渲染工作,之後就可以通過UIWebView來載入HTML的內容了:

    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];    [self.view addSubview:_webView];        //通得模板渲染得到內容(可以隨時修改對應標籤的內容)    NSString *rendering = [self demoFormatWithName:@"標題" value:@"內容"];    NSString *path = [[NSBundle mainBundle] bundlePath];    NSURL *baseUrl = [NSURL fileURLWithPath:path];    [self.webView loadHTMLString:rendering baseURL:baseUrl];

下載GRMustache架構如下:

  

 Code:

#import "ViewController.h"#import <GRMustache.h>@interface ViewController ()@property (strong,nonatomic)UIWebView *webView;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];    [self.view addSubview:_webView];        //通得模板渲染得到內容(可以隨時修改對應標籤的內容)    NSString *rendering = [self demoFormatWithName:@"標題" value:@"內容"];    NSLog(@"\n%@",rendering);    NSString *path = [[NSBundle mainBundle] bundlePath];    NSURL *baseUrl = [NSURL fileURLWithPath:path];    [self.webView loadHTMLString:rendering baseURL:baseUrl];}//給template.html中對應的標籤格式化內容-(NSString *)demoFormatWithName:(NSString *)name value:(NSString *)value{        NSString *fileName = @"template.html";    NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:fileName];    NSString *template = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];    NSDictionary *renderObject = @{@"name":name,@"content":value};    NSString *content = [GRMustacheTemplate renderObject:renderObject fromString:template error:nil];    return content;}@end

列印渲染後HTML內容如下:

2016-12-25 15:21:42.629 JSWeb[1858:83103] <!DOCTYPE html><html lang="zh-cn"><head>    <meta charset="utf-8">    <title>這是一個HTML測試</title></head><body>    <h1> 標題 </h1>    <p> 內容 </p>    <img src="http://img3.redocn.com/20131012/Redocn_2013101208320171.jpg" width="256" height="128"><br><hr></body></html>

webView顯示渲染後的HTML內容如下: 

GRMutstache提供的渲染HTML內容的核心類方法大概有如下這些:

+ (instancetype)templateFromString:(NSString *)templateString error:(NSError **)error;+ (instancetype)templateFromResource:(NSString *)name bundle:(NSBundle *)bundle error:(NSError **)error;+ (instancetype)templateFromContentsOfFile:(NSString *)path error:(NSError **)error;+ (instancetype)templateFromContentsOfURL:(NSURL *)URL error:(NSError **)error;+ (NSString *)renderObject:(id)object fromString:(NSString *)templateString error:(NSError **)error;+ (NSString *)renderObject:(id)object fromResource:(NSString *)name bundle:(NSBundle *)bundle error:(NSError **)error;

作者提供的樣本如:

// Renders "Hello Arthur!"NSString *rendering = [GRMustacheTemplate renderObject:@{ @"name": @"Arthur" } fromString:@"Hello {{name}}!" error:NULL];
// Renders the `Profile.mustache` resource of the main bundleNSString *rendering = [GRMustacheTemplate renderObject:user fromResource:@"Profile" bundle:nil error:NULL];
//Reuse templates in order to avoid parsing the same template several times:GRMustacheTemplate *template = [GRMustacheTemplate templateFromResource:@"Profile" bundle:nil error:nil];rendering = [template renderObject:arthur error:NULL];rendering = [template renderObject:barbara error:NULL];rendering = ...

更多詳情內容查看github上的源碼:https://github.com/groue/GRMustache

本文參考書籍:《iOS開發進階--唐巧》

 

iOS:使用模板引擎渲染HTML介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.