IOS: Rendering the HTML interface using the template engine

Source: Internet
Author: User

In actual development, the UIWebView control accepts an HTML content for the appropriate interface, and the following is the interface for the API:

-(void) loadhtmlstring: (NSString *)string BaseURL: (Nullable Nsurl *) BaseURL

Because HTML content is usually changing, we need to generate the HTML content in memory. It is relatively straightforward to define the basic content of the HTML in a nsstring and then format the content with the [NSString Stringwothformat] method, as shown in the following example:

//format content for the corresponding label-(NSString *) Demoformatwithname: (NSString *) Name value: (NSString *) value{NSString*html =@"<! DOCTYPE html>\n"    ""    """\ n"    "<meta charset=\ "utf-8\" >\n"    "<title> This is an HTML test </title>\n"    ""    "<body>\n"    ""    "<p>%@</p>\n"    " <br>"    "</body>\n"    ""; NSString*content =[NSString Stringwithformat:html,name,value]; returncontent;}

But in fact we can see that this is not comfortable to write because:

1, the template content and code mixed together, neither convenient to read, nor convenient to change;

2, the template content rendering logic using simple [NSString Stringwothformat] to complete, single function. In the actual development, we probably need to do two of raw data processing, and these if the template rendering module can not support, we can only own hand-made shoes this part of the data two processing, time-consuming and laborious. For example, the details page of Weibo, if the delivery time of Weibo is less than 1 days, it needs to be displayed as "xxx hours ago", if less than 1 minutes, it needs to be displayed as "just". The convenient logic for rendering these interfaces is much clearer if it can be extracted into a dedicated typesetting code.

So we need a template engine that is dedicated to the work of this kind of rendering.

Template engine Complex has: Mgtemplateengine (http://mattgemmell.com/mgtemplateengine-templates-with-cocoa/), its template language is more like Smarty, Freemarker and Django. In addition, it is free to define the filter in order to implement the custom rendering logic mentioned above. It needs to rely on Regexkit,regexkit is a regular expression tool class that provides powerful expression matching and substitution capabilities.

It is also simple: Grmustache (Https://github.com/groue/GRMustache), which is more simple than the Mgtemplateengine function. In addition, Grmustache in the open source community more active, updated more frequently.

For the example code above, after using the Grmustache template, we first need to adjust the contents of the template:

1, put the template content in a separate file, easy to change later, such as template.html

2. Replace the original%@ with the form {{name}}.

For example, the modified template content is: (file name: template.html)

<!DOCTYPE HTML><HTMLLang= "ZH-CN"><Head>    <MetaCharSet= "Utf-8">    <title>This is an HTML test</title></Head><Body>    <H1>{{Name}}</H1>    <P>{Content}}</P>    <imgsrc= "Http://img3.redocn.com/20131012/Redocn_2013101208320171.jpg"width= " the"Height= " +"><BR><HR></Body></HTML>

namely template.html

We then read the file into memory in the code and use Grmustache's RenderObject method to generate the rendered HTML content, as shown in the following example code:

//format content for the corresponding label in 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]; returncontent;}

In this way, we have successfully finished rendering the HTML content using the Grmustache template engine, and then we can load the HTML content through UIWebView:

    _webview = [[UIWebView alloc] initWithFrame:self.view.bounds];    [Self.view Addsubview:_webview];         // get content from template rendering (you can modify the contents of the corresponding tag at any time)    NSString *rendering = [self demoformatwithname:@ " title " value:@ " content " ];     *path = [[NSBundle Mainbundle] bundlepath];     *baseurl = [Nsurl Fileurlwithpath:path];    [Self.webview loadhtmlstring:rendering Baseurl:baseurl];

Download the Grmustache framework as follows:

Code:

#import "ViewController.h"#import<GRMustache.h>@interfaceViewcontroller () @property (strong,nonatomic) UIWebView*WebView;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; _webview=[[UIWebView alloc] initWithFrame:self.view.bounds];        [Self.view Addsubview:_webview]; //get content from template rendering (you can modify the contents of the corresponding tag at any time)NSString *rendering = [Self demoformatwithname:@"title"Value@"content"]; NSLog (@"\n%@", rendering); NSString*path =[[NSBundle Mainbundle] bundlepath]; Nsurl*baseurl =[Nsurl Fileurlwithpath:path]; [Self.webview loadhtmlstring:rendering baseurl:baseurl];}//format content for the corresponding label in 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]; returncontent;}@end

Print the rendered HTML content as follows:

 .- A- -  the: +:42.629jsweb[1858:83103] <! DOCTYPE html>"ZH-CN">"Utf-8"> <title> This is an HTML test </title>"http://img3.redocn.com/20131012/Redocn_2013101208320171.jpg"Width=" the"height=" -"><br>

WebView displays the rendered HTML content as follows:

The core class method provided by Grmutstache for rendering HTML content is probably as follows:

+ (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;

Examples provided by the author include:

// renders "Hello arthur!" @" name " @" Arthur " } FromString:@ "Hello {name}}! [ Error:null];
// renders the ' profile.mustache ' resource of the main bundle NSString *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"  === ...

For more details, see Source code on GitHub: Https://github.com/groue/GRMustache

This article refers to the book: "iOS Development Advanced-Tang Qi"

IOS: Rendering the HTML interface using the template engine

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.