| « The Homer Car Syndrome | First bits of Euss 2.0 » |
How to create a template engine in 1 hour
Today I needed to create a mass email sender application for a customer, in order to warn the users of their personal data. The template had some complexity like loops for multi-valued information, thus I needed a template engine.
The goal was to have a text processor which could take an external object model (actually a CSV file) and a template file like ASP.NET does:
Dear <%= firstname %> <%= lastname %>,
This is a set of squares:
<% for (var i=0; i<3; i++) { %>
<%= i %> * <%= i %> = <%= i * i %>
<% } %>
Regards
And the result should look like this:
Dear Sébatien Ros,
This is a set of squares:
0 * 0 = 0
1 * 1 = 1
2 * 2 = 4
Regards
I quickly searched for this sort of tool when I wondered how they would be made. Actually ASP.NET changes the ASPX file into code files which is I suppose the best approach. The only thing I needed was a way to execute this generated code. And guess what, I already have it, it's Jint, again ;)
So the only thing to do is use a simple state machine and a regular expression to convert the previous template to this script :
write('Dear '); write( firstname ); write(' '); write( lastname );
write(',\r\n\r\nThis is a set of squares:\r\n');
for (var i=0; i<3; i++) {
write(' \r\n ');
write( i );
write(' * ');
write( i );
write(' = ');
write( i * i );
write(' \r\n');
}
write('\r\n\r\nRegards');
I also configured Jint so that the write method appends its parameter to a local StringBuilder instance, and took all variables like firstname and lastname to declare them locally in the script. Then I ran the script using Jint and emailed the resulting string to the recipient.
I'm sure I will find even more usages for Jint in the future.