Fallback variables in `dotnet new` templates

Previously, we created our first custom dotnet new template and added our first input parameter for it. Next, let’s get a little more advanced with our parameters to make our life easier. In this post, we’ll create a template symbol that will function like a coalesce operator, taking a preferred input but falling back to a different input if the preferred value is not found.

This is the third in a collection of posts about creating custom templates for the dotnet new system.

Sample code

This is the third in a series of posts about creating custom templates for the dotnet new system. I’ll be working from the results of the prior blog post, but the approach can be used to add this functionality to any dotnet new template. If you want a starter template project to get you going, you can clone the Git repo from that blog post and start from the prior 2-input-parameters template.

Why a coalesce/fallback symbol?

There are bound to be several great reasons to need a fallback variable, or one that coalesces between multiple potential inputs, but here are a few I’ve run across so far.

Provide a generated value with a manual override

If you remember from the case-changing symbol from the prior post, there are symbols that can be computed in some fashion. In that case, we were adjusting the letter casing of another input to be upper-case, but there are several other type: generated symbol options. If you have a default of generating a template value but want to allow the user to submit an override value, the coalesce generator is perfect.

I’ve used this previously when templating a repo license file to generate the copyright year value but allow for a user-submitted override for existing, older projects. (Yes, that is a NuGet package with dotnet new templates for creating more dotnet new templates.)

Provide a fallback to another user-provided symbol

Alternatively, if you have a template value that might need to be set manually, but should adopt a value from another symbol when the manual value isn’t present. This is also easily accomplished with a generator: coalesce symbol by pointing it to the manual input value for the primary symbol and the back-up input value for the fallback symbol.

On a recent project involving a content management system, pages had several YAML values. One value for content would be the full-length title to display at the top of the content page, but there was also a shortened title available for lengthier titles to display in width-constrained locations. If you didn’t need a special shortened variant of the title, you could omit that value and it would simply use the full-length title for both YAML values.

Create a coalesce symbol

At its core, a coalesce symbol has two parameter values: sourceVariableName and fallbackVariableName. These two values can point to any other symbols you have defined, whether they are other input parameters or generated values or a mix of the two.

   "copyrightYear": {
       "type": "parameter"
   },
   "copyrightYearGenerated": {
       "type": "generated",
       "generator": "now",
       "parameters": {
           "format": "yyyy"
       }
   },
   "copyrightYearReplacer": {
       "type": "generated",
       "generator": "coalesce",
       "parameters": {
         "sourceVariableName": "copyrightYear",
         "fallbackVariableName": "copyrightYearGenerated"
       },
       "replaces": "{copyrightYear}"
   },

In this example from the repo license template example mentioned previously, we have a copyrightYear parameter optionally provided by the person generating content. Then, we have a generated four-digit year symbol (e.g., “2018”). Last, there is a coalesce symbol that points its sourceVariableName to the provided parameter but uses the generated value via the fallbackVariableName when a value isn’t provided. The result of this source-plus-fallback coalesce is then used to replace any instances of {copyrightYear} in the template content.

Check your work

If you got lost along the way or need something to compare to, look in the 3-coalesce-parameters folder of the sample Git repo with the resulting templates from following along with this blog post series.

You can now start introducing coalesce, or fallback, variables into your dotnet new templates. As always, there’s so much more that can allow you to do even more advanced things with your templates, some of which I hope to cover in more posts. If there’s something cool that I need to cover, though, reach out to me on Twitter: @patridgedev.

Add variables to your custom `dotnet new` template

Previously, I covered creating your first custom dotnet new template. Now, let’s work on customizing the content our template generates based on inputs provided via the command line. I’ll be working from the same custom template from that post, which is just a dotnet new console output with its own .template.config setup. If you want a starter template project to get you going, use the template from the 1-custom-template folder from the Git repo from that blog post.

This is the second in a collection of posts about creating custom templates for the dotnet new system.

Your first input parameter

When you are generating content from a template, your first parameter for controlling things is built in to the SDK. There are two variables used to decide where to put the generated content: --output and --name. If you provide a path via --output "some/path", the content will be generated in that location. If, in your template’s template.json file, you set "preferNameDirectory": true, you can set the same path via --name "some/path". (If you have the preferNameDirectory variable set to true and provide both an output and name variable, it will use the output value.) Without either command-line parameter, the new content will be generated in the current directory.

Passing in more useful data for your template requires some additional changes to the template.json configuration.

Taking inputs for generating content

To start consuming inputs to alter your generated content, add a new object to the template configuration JSON in template.json.

{
    "$schema": "http://json.schemastore.org/template",
    ...
    "symbols": {
        "helloMessage": {
            "type": "parameter",
            "replaces": "Hello from a new template!"
        }
    }
}

This sets up your template to take a helloMessage parameter via the command line like this.

dotnet new console-awesome --helloMessage "Hello from a command line override!"

The resulting Program.cs file will have a call using our custom parameter.

Console.WriteLine("Hello from a command line override!");

If we don’t pass in that helloMessage parameter, the substitution is made with the value set in a symbol’s defaultValue field.

When the content is generated, it will process the template files and replace all instances of “Hello from a new template!“ with the provided parameter value. We only have one instance here, but you could have several if your template requires it.

Making the output more predictable

Since the template system does a find-and-replace on our symbols defining a replaces value, I want to make sure it doesn’t accidentally find any other instances I didn’t intend for it to replace. To do that, I will typically use a placeholder string that is always replaced, like a template token.

Most template examples I have looked over seem to put default data in the file to be processed and replace that value with the replaces value. I tend to use a placeholder string and a defaultValue within the symbol instead. They both result in the same generated content, so let your own preferences guide you here. I feel like I’m less likely to have identical text elsewhere that will get accidentally replaced as a “false positive” when I use replacement tokens than with actual content.

In the previous example, I would replace the WriteLine parameter in C# with something like Console.WriteLine(”{helloMessage}”) and configure the symbol like this.

{
    "$schema": "http://json.schemastore.org/template",
    ...
    "symbols": {
        "helloMessage": {
            "type": "parameter",
            "replaces": "{helloMessage}",
            "defaultValue": "Hello from a new template!"
        }
    }
}

You will end up creating a symbol for each input you want to accept from the command line, and several more advanced steps. You will also create symbols for some of the processing you wish to do to other inputs, for example changing the letter casing of a provided value.

Changing input parameter casing

There are lots of things we can do to incoming parameter values, but we’ll start with a simple one: forcing something to all uppercase or lowercase. If you’re taking in an input from a user of your template, you can’t always rely on them providing the expected input. For example, if you expect an ID field in your template to have letters in uppercase only, you will want to set it up to enforce that when the templated content is generated.

We add this string modification as a second symbol that will derive a modified value from the original, keeping the original also available if you need it. To do so, return to your .template.config > template.config file.

In the symbols section of the config file, add a new symbol to capitalize the existing helloMessage symbol; I don’t know if there’s a best practice, but I try to name my modifier symbols after what they do. So, in this case, name your new symbol helloMessageUpper. Let’s see what that will look like.

"symbols": {
   "helloMessage": {
       "description": "",
       "type": "parameter",
       "replaces": "{helloMessage}",
       "defaultValue": "Hello from a new template!"
   },
   "helloMessageUpper": {
       "type": "generated",
       "generator": "casing",
       "parameters": {
         "source": "helloMessage",
         "toLower": false
       },
       "replaces": "{helloMessageUpper}"
   }

}

First, we still have our input symbol, helloMessage. Then, we add our new helloMessageUpper symbol. To tell the system we are making a computed symbol, we set the type of our symbol to generated. We then need to tell it what kind ofgeneratorto use:casing` in this case, to tell the system we are going to modify the casing on some other symbol.

When you use a generator symbol, you often require some additional configuration, which is done with a parameters configuration object. In this case, you provide a source symbol, the input to our casing generator, and the direction to adjust the letter casing in a toLower boolean value.

The toLower boolean value doesn’t have any sort of toUpper equivalent. As you might expect, if you set it to true, it will result in a lowercase symbol you can use. What may not be as obvious, though, is that setting toLower to false will result in an uppercase symbol.

With the generator configured, we simply add a replaces value again to tell it what gets our new uppercase-transformed input in the template output.

To test our output, let’s add another line in the template C# source.

Console.WriteLine("{helloMessage}");
Console.WriteLine("{helloMessageUpper}");

Now, we need to install or modified template and generate content from it. From your template directory, make sure you have the latest installed.

dotnet new --install .

If we generate a project from our modified template without any command-line parameters, we get the default symbol value. That default is also fed into the generated symbol for it’s upper-case equivalent.

This command…

dotnet new console-awesome --output TestRunNoParameter

…results in a TestRunNoParameter/Program.cs containing these calls. (Remember, the output parameter will generate the content in a folder with that name, used here to keep our test output organized.)

Console.WriteLine("Hello from a new template!");
Console.WriteLine("HELLO FROM A NEW TEMPLATE!");

And when we provide our own command-line parameter, it substitutes the provided value as above and also passes that value into the upper-case generator.

This command…

dotnet new console-awesome --helloMessage "Hello from a command line override!" --output "TestRunParameterOverride"

…results in these calls in Program.cs.

Console.WriteLine("Hello from a command line override!");
Console.WriteLine("HELLO FROM A COMMAND LINE OVERRIDE!");

Check your work

You can now start introducing variables into your dotnet new templates. If you want to compare your work to a template created by following along, check out the 2-input-parameters folder of the GitHub repo created for this blog post series.

There’s so much more that can allow you to do even more advanced things with your templates, some of which I hope to cover in more posts. If there’s something cool that I need to cover, though, reach out to me on Twitter: @patridgedev.

Making a custom ‘dotnet new’ template

Why make a template

I am a bit biased these days, but once I spin up a folder structure and/or text document manually more than twice, I give some thought to templating it. If I need to keep making more of something, the time to get all the boilerplate content in place is time taken away from the good stuff I want to write.

This is the first in a series of posts about creating custom templates for the dotnet new system.

How to template

There are lots of templating systems out there that can allow you to create content quickly. If you have used any of the ASP.NET generators, those use Yeoman to spin up new ASP.NET projects quickly. I’m not saying any template engine is better here, just showing what I’ve been using lately.

I have been using the templating engine built into the .NET Core SDK, since it tends to be installed on all my development machines. The .NET Core template system is exposed through the dotnet new command-line program, where the dotnet program is able to do way more stuff like compiling code, managing NuGet packages, or running .NET Core applications. (Run dotnet --help to see a list of all the SDK commands available to you.)

That said, if you need to be able to create content from templates in an environment where you don’t want the full .NET Core SDK installed, you may want to consider other alternatives, or research how to put just a core templating engine into your own tools and deliverables.

Get started with .NET Core SDK

You can get the .NET Core SDK installed on macOS, Windows, and Linux. I have it on my MacBook, a couple Windows 10 machines, and a Raspberry Pi or two. If you work with Visual Studio 2017 or Visual Studio for Mac, you may have it installed already, too. From your favorite command line, run the following command to get the current installed .NET Core SDK version on your machine.

dotnet --version

If that fails for you, you can still join in the fun. Run over to the .NET getting-started guide and click the download link. That link should land you in the right spot for your current platform. After you install the SDK, you may need to close and relaunch any command line windows you had open previously.

Once you have the .NET SDK installed, give that command another run to make sure everything is happy. I am running version 2.1.300, which is the latest release as of writing this. If you got something like 2.1.###, you should be able to do everything I’m doing here (taken with a big Works on My Machine™ disclaimer).

Create a project

The default .NET Core SDK installation will give you some initial templates if you want to give them a shot. To list all the available templates, just run the following command with no parameters.

dotnet new --list

You should have at least some .NET Core templates for console apps, test projects, and ASP.NET projects. Let’s spin up a .NET Core console app. Each of the templates has a “short name” you can pass to dotnet new. If you use a template without any parameters, it will put all the resulting files in your current directory. In this case, this command will create a C# project file named after the current directory and code file (as well as some results in /obj because it also does a NuGet restore).

dotnet new console

Don’t worry, though. If you run this command in a directory where you have conflicting files, it won’t overwrite them. You’ll get an error for any conflicts.

So you don’t have to worry about polluting your current directory, you can give the command another option to drop the template output into a new destination.

dotnet new console --output MyConsoleApp

With the --output parameter and value, the result will be put in the /MyConsoleApp folder.

While many of these templates create projects you can immediately compile and/or run, that certainly isn’t a requirement. In this case, you could run the following commands to execute the resulting console project.

cd MyConsoleApp
dotnet run MyConsoleApp.csproj

I want my own template

Now we can start having fun. Let’s say you need to make your own console template. The only difference between the console project we generated and a template of our own is a .template.config folder containing a template.json file. First, make a change to your MyConsoleApp project to make it your own. A simple-yet-noticeable change would be to edit Program.cs to output your own phrase. In my case, I changed the Console.WriteLine call to this.

Console.WriteLine("Hello from a new template!");

Now, we just need the template configuration.

Create a new folder in MyConsoleApp called .template.config.

Open your favorite text editor and create a new file. Save it to the .template.config folder as template.json. This JSON file is just the configuration for our template. Here is a sample of the bare minimum this file we might use for our console app template.

{
    "$schema": "http://json.schemastore.org/template",
    "author": "Adam Patridge",
    "classifications": [ "Console" ],
    "identity": "PatridgeDev.TemplateBlogging.Console.CSharp",
    "name": "Our slightly modified console app",
    "shortName": "console-awesome"
}

The $schema value is always the same. This just tells compatible IDEs how to offer assistance when creating these documents. For example, Visual Studio Code will use the schema to offer some IntelliSense to us.

The author value is you.

The classifications value is an array of descriptions you might use for your project. Not going to lie, while these are listed when you do dotnet new --list, I have yet to figure out how to query them, or if you even would before you have dozens of templates.

The identity value is just a unique name for our template within the dotnet new list. You can use some sort of reverse-DNS notation as I did or just about anything. (There seems to be a trend to put language in the last portion, but that is likely only needed if you have multiple language versions of a single template.)

The name value is the user-visible name for your template.

Lastly, the shortName value is the name people can use when creating things from templates via command line, in the form of dotnet new {shortName}.

Customize the JSON fields to your liking and save the result. With that file in place, we can load our template into the .NET Core SDK with a single command.

dotnet new --install .

This command will install the current directory (.) as a template. If your command line’s current directory is somewhere other than the template, adjust accordingly.

Once you have your template installed, you should see it show up in the list with dotnet new --list. (It also should have output the list after successfully installing the template.)

Templates                                                       Short Name          Language        Tags
--------------------------------------------------------------------------------------------------------------------------
Console Application                                             console             [C#], F#, VB    Common/Console
…
Our slightly modified console app                               console-awesome                     Console

With our custom template in the list, we can generate a new version of our modified console app now.

dotnet new console-awesome --output ../MyNewAwesomeConsoleApp

This will generate a console app from our template in a sibling folder to our template folder. If you wish to generate the console app elsewhere, adjust the path provided to the --output parameter.

Look for your modified line(s) to verify everything generated as expected.

Technically, we have taken a fairly complex template we know nothing about internally and turned it into a completely static template. That’s progress, right? We’ll work on making our templates customizable another time.

Other installation options

The dotnet new --install command can accept a path to a folder, as we are providing here. It can also accept a path to a local NuGet package (.nupkg) or even a NuGet package ID from nuget.org. For example, I’m working on some templates to help with creating new template and adding files to Git/GitHub repos. This command would install those templates from NuGet directly.

dotnet new --install dotnet_new_template_creator

Once you have a template you want to share with folks, you can wrap it up in a nupkg file and send it to them directly or via publishing it to nuget.org.

[optional] Uninstalling your template

I won’t pretend this new custom template is incredibly useful, so let’s make sure we can clean up our test efforts from the dotnet new options. If you install a template from a folder location, you uninstall it from an absolute path to that folder location using dotnet new --uninstall. For example, if I was working at ~/Projects/, my uninstall command would be the absolute form of that path and look like this, with your username instead of {username}.

dotnet new --uninstall "/Users/{username}/Projects/MyConsoleApp"

If you installed a template from a nupkg or NuGet directly, you pass in the package ID. And, if you are ever unsure how a template was installed, you can get a list of all the valid uninstall parameters with an empty --uninstall command.

dotnet new --uninstall

Check your work

If you got lost along the way or need something to compare to, look in the 1-custom-template folder of the sample Git repo with the resulting templates from following along with this blog post series.

Next steps

That’s the basics to getting started with your own dotnet new templates, but there are so many parts of the templating system that could have their own blog posts. In later posts, I’m hoping to explore some of the more complex features of the template config. If there’s something cool that I need to cover, reach out to me on Twitter: @patridgedev.