How to use the fileinputname parameter inside your template items in Visual Studio

A Visual Studio Item Template allows us to generate new files with code, so that we avoid having to manually create them. This automatization is very practical when we need to create similar classes more than one time. A template is being offered as option in the “Add new item” dialog of Visual Studio:

Add new item dialog in visual studio

We pick a name for the new item and we add it to our project.

Based on the definition we did in the .vstemplate file a number of new files is going to be generated. In the following example we are creating three new classes in three different folders (the folders are created automatically if they do not yet exist). As you can see we use the fileinputname parameter extensively. This parameter contains the name we wrote when we were creating the item template:

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
  <TemplateData>
    <DefaultName>DemoName.cs</DefaultName>
    <Name>Demo Template</Name>
    <Description>This is a template for creating boilerplate code.</Description>
    <ProjectType>CSharp</ProjectType>
    <SortOrder>10</SortOrder>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <References />
    <ProjectItem SubType="" TargetFileName="Repositories\$fileinputname$Repository.cs" ReplaceParameters="true">DemoRepository.cs</ProjectItem>
	  <ProjectItem SubType="" TargetFileName="Models\$fileinputname$Model.cs" ReplaceParameters="true">DemoModel.cs</ProjectItem>
	  <ProjectItem SubType="" TargetFileName="Interfaces\I$fileinputname$Repository.cs" ReplaceParameters="true">IDemoRepository.cs</ProjectItem>
	<CustomParameters>  
      <CustomParameter Name="$InputName$" Value="$fileinputname$"/>
    </CustomParameters>  
  </TemplateContent>
</VSTemplate>

The most important line is the definition of a CustomParameter. The name of this parameter is up to you and you can use it inside your files as a placeholder for the fileinputname parameter. Here is an example of the DemoRepository.cs template class:

using $rootnamespace$.Interfaces;
using $rootnamespace$.Models;

namespace $rootnamespace$.Repositories
{
    public class $InputName$Repository : I$InputName$Repository
    {
        public $InputName$Repository()
        {
        }
    ...
    ...
    ...

The InputName will be replaced with the name we picked when we created the item template.

The reason why we use a custom parameter and not the fileinputname directly inside our files can be found in this StackOverflow article.

comments powered by Disqus