Razor from a console - calling child templates

16.07.2010 14:09Comments
In my previous post I showed how to run a Razor template (.NET's new view engine) from a console app in order to generate code. In this post I will demostrate how to run another razor template from within a razor template. This is actually quiet simple, and since we already have the "RazorClient.dll" referenced in the RazorFactory code, we can achieve this with the following code (this goes inside a razor template): Snippet
@{
	var factory = new RazorClient.RazorFactory();

	using (var template = factory.Create<RazorClient.FileWriter>(@"C:UsersGusDocumentsVisual Studio 2010ProjectsConsoleApplication1ConsoleApplication1Test2.txt"))
	{

		if(factory.Errors.Length > 0)
		{
			//do something
		}
		else
		{
			template.FilePath = @"C:UsersGusDocumentsVisual Studio 2010ProjectsConsoleApplication1ConsoleApplication1Test2.txt.out.txt";
			template.Execute();
		}
	}
}
Notice how we need to include the namespace of the classes like in RazorClient.RazorFactory. This code being so easy led me to the idea of having a main razor file to act as a project and fire the rest of the templates. And I took advantage of the fact that we are firing the rest of the templates from a Razor file to generate a report that showed the status of each template in HTML format. Here is a sample: Snippet
<html>
<head>
	<style type="text/css">
	.success
	{
		background-color: green;
	}

	.failed
	{
		color: white;
		background-color: red;
	}
	</style>
</head>
<body>
<h1>My project name here</h1>
<p>
Project generated on @DateTime.Now
</p>
<table>
<tr>
<td>Template</td>
<td>Status</td>
<td>Errors</td>
</tr>

<tr>
<td>Test2.cshtml</td>
@{
	try
	{
		//this is my block code.
		var factory = new RazorClient.RazorFactory();
		using (var template = factory.Create<RazorClient.FileWriter>(@"C:UsersGusDocumentsVisual Studio 2010ProjectsConsoleApplication1ConsoleApplication1Test2.txt"))
		{
 			if(factory.Errors.Length > 0)
			{
				this.Write("<td class='failed'>Failed</td>");
				this.Write("<td>");
				foreach(var t in factory.Errors)
				{
					this.Write(t);
					this.Write("<br />");
				}
				this.Write("</td>");
			}
			else
			{
				template.FilePath = @"C:UsersGusDocumentsVisual Studio 2010ProjectsConsoleApplication1ConsoleApplication1Test2.txt.out.txt";
				template.Execute();
				this.Write("<td class='success'>Successful</td><td></td>");
			}
		}
	}
	catch(Exception ex)
	{
		this.Write("<td class='failed'>Failed</td>");
		this.Write("<td>");
		this.Write(ex.ToString());
		this.Write("</td>");
	}
}
</table>
</body>
</html>
When I ran this main template, the following html was generated (you might want to tune it up a little, html design is not my thing :)):

My project name

Project generated on 7/16/2010 10:44:33 AM
Template Status Errors
Test2.txt Successful
So in this post I showed that having a main template to fire the rest of the child templates is a good idea.

comments powered by Disqus