CodeSmith Tips & Tricks: Template Recursion

Here is a simple CodeSmith template that shows how templates can be recursively called, have indentation levels and render to a single output:

<%@ CodeTemplate Language="C#" TargetLanguage="C#" ClassName="RecurseSampleTemplate"  %>
<%@ Property Name="InRecurse" Type="System.Boolean" %>
// Sample header
<% if (this.InRecurse) { %>
// Nested class
<% } else { %>
// Parent class
<%
    RecurseSampleTemplate recurseSample
= new RecurseSampleTemplate();
    recurseSample.InRecurse
= true;
    recurseSample.Response.IndentLevel
= this.Response.IndentLevel + 1;
    recurseSample.Render(
this.Response);
}
%>

Notice how on the CodeTemplate directive we are setting the class name for the template.  Then we can create another instance of the template in code, set some properties on the new instance and render it to the current response object.

Here is what the output of this template looks like:

// Sample header
//
Parent class
//
Sample header
//
Nested class

No Comments