Those who have used CodeSmith are already aware how it works. We will see how the engine really works behind.
EndUser writes templates ASP style in preferred Language (C#, VB etc.)
And the Parser parses the template and Generates the Output.
To explain what I am trying to say,
An example Template May be (Example in C#) :
Test Template
<%for (int i=0; i<5; i++)
{%>
This is Test: <%=i.ToString()%>
<%}%>
Example Output for the above template is:
Test Template
This is Test: 0
This is Test: 1
This is Test: 2
This is Test: 3
This is Test: 4
This is Test: 5
What we need to do to achieve this is:
Template => Parser => Generated Code in Preferred Language => Run using the CodeDom / Compiler => Generate Output as Text
So for the Above Template a Parser will generate something similiar like this in C#:
using System;
using System.IO;
using System.Text;
namespace TestTemplate
{
///
/// Summary description for ParseManager.
///
public class Testing
{
public Testing()
{
//
// TODO: Add constructor logic here
//
}
public static string Render()
{
MemoryStream mStream = new MemoryStream();
StreamWriter writer = new StreamWriter(mStream,System.Text.Encoding.UTF8);
writer.Write(@"
Test Template
" );
for (int i=0; i<10; i++)
{ writer.Write(@"
This is Test: " );
writer.Write(i.ToString()); writer.Write(@"
" );
} writer.Write(@"" );
StreamReader sr = new StreamReader(mStream);
writer.Flush();
mStream.Position = 0;
string returndata = sr.ReadToEnd();
return returndata;
}
}
}
The Generated Code should be passed to CodeDomProvider for C# [in this case: CSharpCodeProvider() ] and run the code dynamically to generate the OUTPUT mentioned above.
So the Parser plays important role here to prepare the correct code in the preferred language. So if we want to give multi language Template writing feature ie. in VB, Delphi, Php name any language. We would have to write the correct Parser for these Languages. And depending on the Users Preferred Language we need to pass the Generated code to the correct Compiler too. Then if we dynamically compile and Run the Generated Code we will get the desired output.
The good news is in .Net dynamic code compilation and running is very easy. You may prefer to look at the System.CodeDom Namespace.
CodeSmith follows same concept that I have shown here.