March 06, 2013

Use HTML Templating for more than just HTML

Templating Engines are cool, but why are they F**KING AMAZING!?!?! The reason is you can use them for much more than templating your websites. Whether it is xml, RSS feeds, email templates, letters, you can use templating for ANYTHING and I will show you how.

So, the initial thing that makes them awesome is that they allow you to write HTML.

The pieces you have to remember with templating is that you get it an “Entity” or model. In the case above it is “blog” . This model is used to provide the dynamic data to generate. The neat things with models is that you can add ANYTHING, property, functions, hell you could even add logic to say if this value is null, then just display “no blog” if you wanted. Templates blur the line of business logic and view logic.

Great, I got it working in my site, but what else can I do with this templating stuff? What if I told you, you could use that same HTML template and use it to display as an email out to a user:

And don’t stop there, the only reason why I have an RSS feed is that I created a template to post my blog.

Now, all those things, I just told you about, you could use with handlebars, EJS (which I use), Jade and many more. But how does this help me with my programming in server side code? Well, at least for C#, enter Razor Engine . Razor engine is awesome because now it allows you to defer some code to be executed at runtime. More specifically, I had some issues where we have to deliver documents to many different investors, and each investor has different naming conventions. Razor would allow you to defer programming this until later, WITHOUT STOPING YOUR APP AT ALL. MIND BLOWN!!! Let’s take a look:

Here we show some code that configures a name for a specific user, actually that code would build “Jorden.tif”. But what if the client wants us to create a manifest file of all the files that we just named, lets edit some of the code to add a file write:
And the beauty of all this, NO CODE CHANGES TO PROD, just change the template you feed it and let it rip. Check it out for yourself and be the judge, you’ll find out that it is another tool in the tool box for flexible code.