views:

137

answers:

1

Hi,

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 that 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!

+2  A: 

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.

Jasarien
I'm with you when it comes to creating the HTML file and loading it into a NSMutableString, but where I'm having a hard time is using `replaceOccurencesOfString:` the thirty-something times it would take for all of the variables that have to be replaced. I'm wondering if there is some sort of a category out there on NSString or NSMutableString that can apply values from a KVC-compliant object to "tags" specified in the template. Any ideas?
Babe Smith