开发者

HTML Email Template as NSString

I am adding functionality to my app that will allow it to email some rather detailed information. I would like to send this as an HTML-formatted email so that I can take advantage of HTML and CSS styling.

The approach I'd like to take is to design the template with placeholders for the fields to be filled in, load the template into an NSString, then use string replacement to change out the placeholders with the actual data.

Rather than having one huuuuuuge line such as:

NSString *emailTemplate = [NSString stringWithFormat:@"<h1>TITLE</h1><hr noshade/><p>Here is the information about the thing th开发者_C百科at you are interested in. Find more from the table below:</p> . . ."]

I'd like to do this in a more elegant way. Should I write the template into a file then load it? What's the best way to do this?

Also, how could I do this in a localize-able way?

Thanks!


I'm not sure about the best way to do this in a localisable way, but it would be a lot more beneficial for you to write the HTML into it's own .html file, and read the contents of that file into an NSMutableString object when you need it.

You can do this using

+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error

If you use this method, you'll need to call mutableCopy on the returned string, so that you can do the string replacement later. Don't forget that using mutableCopy will return a new NSMutableString object that you'll be responsible for releasing when you're finished with it.

Then you can go ahead and use

- (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)opts range:(NSRange)searchRange

To replace the placeholders with your content.

The advantages of doing it this way means that you can easily edit the HTML using a WYSIWYG editor, or your favourite IDE, without changing the code in your app. You can also preview what it'll look like much easier this way.


Take a look at Matt Gemmell’s implementation, MGTemplateEngine. It works on OS X and iOS. The original seems to be hosted on SVN only, so someone git-svn'ed it to Github.

I needed to tinker with the build settings before it compiled, but it works like a charm and is pretty powerful (indeed, way more powerful than I, and presumably also you, needed).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜