Photo by pxhere.com

Create your own Xamarin project template

Start your project faster thanks to .Net Core!

Posted by Damien Aicheh on 06/12/2018 · 4 mins

After many different projects, you probably noticed that you always use the same Nugets packages, a project structure often similar, your own class extension, the same configuration for your database connection… All that kind of stuff that help you to build a project more easily.

This work proves to be repetitive, boring and a waste of time. In this tutorial we will see how to easily create our own project template that we can then use at each start of new Xamarin project.

Preparation

Our template

First of all, we need to create a new Xamarin project (Forms or/and Native) and configure it with all that will then allow us to start a new project without wasting time. Mine will be named Template.Xam. Once this project is ready we can move on to the next step.

Install .Net Core

To generate our template, we first need to install .Net Core SDK.

Some base commandes :

Let’s open a command terminal, and if everything was installed correctly, we can check the version installed with the command :

dotnet --version

To consult the available templates, just run the command:

dotnet new -l

Installing our template

Now, it’s time to setup our project Template.Xam in order to be able to generate our projects with dotnet.

Template configuration

We need to create a folder in our root project directory called .template.config. In this folder, let’s create a file configuration for our template called template.json.

Here is the configuration to add to this file:

{
    "$schema": "http://json.schemastore.org/template",
    "author": "Damien Aicheh",
    "classifications": [ "Xamarin" ],
    "identity": "MyXamarinTemplateProject",
    "shortName": "MyXamarinTemplate",
    "name": "Starter project for my Xamarin applications",
    "tags": {
	    "language": "C#",
	    "type": "project"
	  },
    "sourceName": "Template.Xam",
    "preferNameDirectory": true
}

Here is a summary of the different keys of this JSON:

shortName : It’s the name of our template that we will see in our available templates list. This key will be used to generate our project, it is therefore better to keep its value simple.
sourceName : This must match our template name : Template.Xam, this name will be replaced by the generator with the name of the project generated.
name : It corresponds to the description that will appear in our available templates list.

Once the configuration of the template done it has to be installed:

dotnet new --install ./path/to/Template.Xam

If everything went well, the template is visible in the list of available templates.

Generate a new project

We can now generate a new project with the following command line :

dotnet new MyXamarinTemplate -o YourProjectName

Happy coding!

Do not hesitate to follow me on to not miss my next tutorial!