UIWebView-iOS中使用模板引擎渲染HTML界面_html/css_WEB-ITnose
在iOS实际的开发中,使用UIWebView来加载数据使用的场景特别多。很多时候我们会动态的从服务器获取一段HTML的内容,然后App这边动态的处理这段HTML内容用于展示在UIWebView上。使用到的API接口为:
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
由于HTML内容通常是变化的,所以我们需要动态生成HTML代码。通常我们从服务器端获取到标题、时间、作者和对应的内容,然后我们需要对这些数据处理之后拼接成一段HTML字符串。对于传统的做法是将上面的需要替换的内容填写一些占位符,放到指定的文件中如(content.html),如下所示:
<!DOCTYPE html><html> <head> <title>key_title</title> </head> <body> <div> <div> <h2 id="key-title">key_title</h2> <div>key_date key_author</div> <hr/> </div> <div>key_content</div> </div> </body></html>
然后在指定的地方使用如下的方式动态生成HTML代码:
- (NSString *)loadHTMLByStringFormat:(NSDictionary *)data{ NSString *templatePath = [[NSBundle mainBundle] pathForResource:@"template" ofType:@"html"]; NSMutableString *html = [[NSMutableString alloc] initWithContentsOfFile:templatePath encoding:NSUTF8StringEncoding error:nil]; [html replaceOccurrencesOfString:@"key_title" withString:data[@"title"] options:NSCaseInsensitiveSearch range:NSMakeRange(0, html.length)]; [html replaceOccurrencesOfString:@"key_author" withString:data[@"author"] options:NSCaseInsensitiveSearch range:NSMakeRange(0, html.length)]; [html replaceOccurrencesOfString:@"key_date" withString:data[@"date"] options:NSCaseInsensitiveSearch range:NSMakeRange(0, html.length)]; [html replaceOccurrencesOfString:@"key_content" withString:data[@"content"] options:NSCaseInsensitiveSearch range:NSMakeRange(0, html.length)]; return html;}
生成界面如下
在实际的使用中发现还是存在不少的问题,比如我们需要对数据进行预先处理的时候需要写大量的
- (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange;
这样的替换,而且对于一些特殊的字符还需要进行特殊处理等,实在不是太友好,这样就需要一个引擎来专门处理这些事情,本文主要介绍MGTemplateEngine和GRMustache的使用。
MGTemplateEngineMGTemplateEngine是AFNetworking的作者Matt的作品,它是一个比较流行的模板引擎,它的模板语言比较类似于Smarty、FreeMarker和Django。另外它可以支持自定义的Filter(以便实现自定义的渲染逻辑),需要依赖正则表达式的工具类RegexKit。
创建模板
<!DOCTYPE html><html> <head> <title>fs_title</title> </head> <body> <div> <div> <h2 id="fs-title">fs_title</h2> <div>fs_date fs_author</div> <hr/> </div> <div>fs_content</div> </div> </body></html>
// 第二种MGTemplateEngine MGTemplateEngine *engine = [MGTemplateEngine templateEngine]; [engine setDelegate:self]; [engine setMatcher:[ICUTemplateMatcher matcherWithTemplateEngine:engine]]; NSString *templatePath = [[NSBundle mainBundle] pathForResource:@"MGTemplateEngineTemplate" ofType:@"html"]; // 第一种赋值方式 [engine setObject:variables[@"title"] forKey:@"title"]; [engine setObject:variables[@"author"] forKey:@"author"]; [engine setObject:variables[@"date"] forKey:@"date"]; [engine setObject:variables[@"content"] forKey:@"content"]; NSString *htmlString = [engine processTemplateInFileAtPath:templatePath withVariables:nil]; // 第二种赋值方式 // Process the template and display the results.// NSString *htmlString = [engine processTemplateInFileAtPath:templatePath withVariables:variables]; NSLog(@"Processed template:\r%@", htmlString); [self.webView loadHTMLString:htmlString baseURL:nil];
说明
(1)MGTemplateEngine提供的示例程序是运行在Mac OS上的,如果要使用到iOS上面需要引入Foundation框架,还需要个UIKit (2)对于运行在Xcode6以上的环境下创建的工程由于没有PCH文件可能会报错,需要在MGTemplateEngine的各个头文件中引入Foundation框架 (3)MGTemplateEngine在GitHub上的地址为https://github.com/mattgemmell/MGTemplateEngine。(4) 如果要算出这个webview的高度 在div加上
NSString *heightString = [webViewstringByEvaluatingJavaScriptFromString:@"document.getElementById(\"container\").offsetHeight;"];
GRMustacheGRMustache使用方法 《GRMustache Document》
举个例子
A typical Mustache template:模板Hello fs_nameYou have just won fs_value dollars!fs_#in_caWell, fs_taxed_value dollars, after taxes.fs_/in_ca
{ "name": "Chris", "value": 10000, "taxed_value": 10000 - (10000 * 0.4), "in_ca": true}
Hello ChrisYou have just won 10000 dollars!Well, 6000.0 dollars, after taxes.
代码:
NSString *template = [[NSBundle mainBundle] pathForResource:@"MGTemplateEngineTemplate" ofType:@"html"];// 注意要对路径进行UTF8编码 不然会有问题NSString *templatePath = [NSString stringWithContentsOfFile:template encoding:NSUTF8StringEncoding error:nil];NSString *htmlString = [GRMustacheTemplate renderObject:variables fromString:templatePath error:nil];[self.webView loadHTMLString:htmlString baseURL:nil];

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









이 기사는 HTML & LT; Datalist & GT에 대해 논의합니다. 자동 완성 제안을 제공하고, 사용자 경험을 향상시키고, 오류를 줄임으로써 양식을 향상시키는 요소. 문자 수 : 159

이 기사는 HTML & lt; Progress & Gt에 대해 설명합니다. 요소, 그 목적, 스타일 및 & lt; meter & gt의 차이; 요소. 주요 초점은 & lt; progress & gt; 작업 완료 및 & lt; meter & gt; Stati의 경우

이 기사는 HTML & lt; meter & gt에 대해 설명합니다. 범위 내에 스칼라 또는 분수 값을 표시하는 데 사용되는 요소 및 웹 개발의 일반적인 응용 프로그램. & lt; meter & gt; & lt; Progress & Gt; 그리고 Ex

이 기사는 모바일 장치의 반응 형 웹 디자인에 필수적인 Viewport Meta Tag에 대해 설명합니다. 적절한 사용이 최적의 컨텐츠 스케일링 및 사용자 상호 작용을 보장하는 방법을 설명하는 반면, 오용은 설계 및 접근성 문제로 이어질 수 있습니다.

이 기사는 & lt; iframe & gt; 외부 컨텐츠를 웹 페이지, 공통 용도, 보안 위험 및 객체 태그 및 API와 같은 대안을 포함시키는 태그의 목적.

이 기사는 html5 & lt; time & gt; 시맨틱 날짜/시간 표현 요소. 인간이 읽을 수있는 텍스트와 함께 기계 가독성 (ISO 8601 형식)에 대한 DateTime 속성의 중요성을 강조하여 Accessibilit를 향상시킵니다.

기사는 HTML5 크로스 브라우저 호환성을 보장하기위한 모범 사례에 대해 논의하고 기능 감지, 점진적 향상 및 테스트 방법에 중점을 둡니다.

이 기사에서는 브라우저에서 직접 사용자 입력을 검증하기 위해 필요한, Pattern, Min, Max 및 Length 한계와 같은 HTML5 양식 검증 속성을 사용하는 것에 대해 설명합니다.
