cocoa

NSConference

Last week I attended NSConference in Atlanta and had a really great time. There were many great speakers, I’m leaving out many, but a few sessions that come to mind include:

String template processing in your native Cocoa and Cocoa Touch applications with MGTemplateEngine

Tagged:  

Template engines are common in web applications and there are many options such as Smarty, FreeMarker, etc.

It may not be immediately obvious but the can also be really useful in native iPhone Cocoa Touch and Desktop Cocoa applications. It can be even more important now that native applications are integrating more and more with functionality using UIWebView and WebView.

They can be particularly useful to generate

  • text or HTML emails for reports, invoices, etc.
  • XML or formatted data to be exported or sent to another application

You can try to do it [NSMutableString appendFormat] or maybe with [NSString localizedStringWithFormat] but it really easy to do with a template engine such as MGTemplateEngine by the prolific Matt Gemmell.

There is some helpful documentation included with the code but the basic steps are:

  1. add MGTemplateEngine code to your project
  2. add libicucore to your target
  3. Use the MGTemplateEngine to generate a formated string (described below)
  4. Display or email the formatted string.
  5. To use the template engine you'll need a template file. In this case I'm using an HTML template but it can be any format (text, xml) that you like. In this example I'm using an extremely simple HTML template. Note that the variables to be substituted are demarcated by dual curly braces {{ totalNumberOfParts }} and the for loop by a curly brace and percent sign {% for part in parts %} . Note also the {% /for %} that ends the for loop.

    In our Objective-C program its pretty simple to use the template engine to process the templates with a dictionary of variables that we provide.

    If there is a tricky part to using the MGTemplateEngine is that if you make a mistake in the template such as forgetting the /for you'll only get an obscure error such as.
    Previous frame identical to this frame (gdb could not unwind past this frame)
    But with this heads up you'll know to study the template for any syntactical issues.

    All in all it is a great framework that has really helped me in a couple of applications. Thanks Matt for this really useful code. It has saved me a bunch of time.

Syndicate content