Writing templates

A CodeSmith Generator template (.cst file) mixes static text with code that runs when you generate. The syntax is close to ASP.NET: directives configure the template, code blocks control what is written, and expressions insert values into the output. The output can be any text at all, such as C#, VB, SQL, HTML or XML.

Template syntax at a glance

Syntax What it does Learn more
<%@ ... %> A directive. Configures the template (CodeTemplate), declares properties (Property, XmlProperty), references assemblies and namespaces (Assembly, Import) and registers sub-templates (Register). The CodeTemplate directive
<% ... %> A code block. Runs code in the template's language, such as loops and conditions around static text. Property validation
<%= ... %> An expression. Writes a value to the output. Declaring and using properties
<script runat="template"> ... </script> A script block. Adds members (methods, properties, overrides) to the template class. The CodeTemplate object
<%-- ... --%> A template comment. Never appears in the output. Including comments
<%% Writes a literal <% to the output. Escaping ASP.NET tags
<!-- #include file="..." --> Inserts the contents of another file into the template. Including external files

Here's a small C# template that uses most of these pieces. It declares two properties, writes an optional namespace around a class and names the output file after the class:

<%-- Generates an empty class. --%>
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Generates an empty class." %>
<%@ Property Name="ClassName" Type="System.String" Category="Context" Description="The name of the class to be generated." %>
<%@ Property Name="ClassNamespace" Type="System.String" Optional="True" Category="Context" Description="The namespace that the generated class will be a member of." %>
<% if (ClassNamespace != null && ClassNamespace.Length > 0) { %>
namespace <%= ClassNamespace %>
{
<% } %>
public class <%= ClassName %>
{
}
<% if (ClassNamespace != null && ClassNamespace.Length > 0) { %>
}
<% } %>
<script runat="template">
public override string GetFileName()
{
    return ClassName + ".cs";
}
</script>

Tip

If you've never written a template, start with the Writing your first template tutorial, then come back here for the details.

Learning path

1. Basic template syntax

Basic template syntax covers what every template uses:

2. Advanced template syntax

Advanced template syntax helps you organize larger code generation projects:

3. Driving templates with metadata

Driving templates with metadata shows where the input to your templates can come from: