Creating Templates with Liquid in ASP.NET Core

Comments 0

Share to social media

Templating has been an essential feature for quite a while. At the heart of the problems that software development often attacks, creating simpler ways of dealing with and eliminating repetition is very important. Templates are, in fact, an old way of dealing with something that modules, packages and component libraries do today. It allows the famous “reuse”.

In the ASP.NET world, many template engines have come and gone. The most famous, Razor, is the standard used by most of the industry today, under the microscope of Microsoft. From NHaml, Spark View Engine to RazorEngine, everyone has (and some still have) a large space in the community.

However, this article deals with Liquid. Liquid is an open-source template language created by Shopify and written in Ruby. As you may have noticed, it is broadly used by Shopify and some of the correlated projects and companies. It’s very mature as well, being out there since 2006.

With Liquid, you can run code directly from a database, for the cases when you have a remote client that needs to update part of the code, for example. It also offers a good error handling system, while it’s very clean and performs well.

Take a look below at the final example you will have created by the end of this article. Figure 1 shows the listing page of a single CRUD operation (that will only add new data) of employees, while Figure 2 displays the registration page. You can find the completed project here.

Figure 1. Listing the employee’s records.

Figure 2. Registering new employees.

Creating the project

The first thing to do is to create a new project via Visual Studio. Although this type of resource works with other versions of ASP.NET web projects, this example will be an ASP.NET Core Web Application project, because it will give more comparative inputs between the Razor model and the current model with Liquid.

To do this, go to the option that creates a new project, and select the option as shown in Figure 3, and click Next.

Figure 3. Creating a new ASP.NET Core Web Application.

The next screen will ask you to fill the project name, the location and the solution name, respectively. Fill all of them according to Figure 4 and click Create.

Figure 4. Configuring project’s definitions.

The project will take a while to load and, then, open a new window like that shown in Figure 5.

Figure 5. Selecting the proper project template.

You can also perform this whole process through the command line, by the use of the dotnet command.

Once you have finished, it’s time to install the NuGet package regarding the Liquid dependency. For this, run the following command by going to the menu Tools > NuGet Package Manager > Package Manager Console:

This example will use the Fluid.MvcViewEngine version 1.0.0-alpha-9637. You can check for the latest available option here.

Startup settings

Before you begin coding, you need to create the template for the Employee class. To do this, create a class in the Model directory called Employee.cs. Its content will be very simple, containing only the attributes that will be used in the CRUD commands for the Employee object:

Listing 1. Code of the Employee class.

Next, you need to configure the Startup class. It is here that you should define the service configuration for the Fluid API, as well as register the new employee model.

Listing 2. Code of the Startup class.

The using statements at the beginning of the class are already optimized without unnecessary imports. The Fluid API provides the tools to register as many models as you need to work in the templates. If your application needs several different models, all of them must be set here.

If you have decided to go with an MVC version of the web project, make sure to compare the distinctions between both files.

Next, you need a repository layer to provide a storage mechanism. For instance, this project won’t make use of any database or API-like resource for data saving. A simple in-memory list of employees will do the job to avoid outer complexities (Listing 3). Put this class into a new folder called Repositories.

Listing 3. Code of the EmployeeRepository class.

Feel free to adjust this layer to your own needs. Next, you need to create a new employee’s controller or, if you want, to adapt the then-created home controller. It will handle the operations regarding the endpoints that will communicate with the Liquid templates.

Listing 4 shows the code for the EmployeeController. You must maintain the same name since you’ll call it this way in the templates.

Listing 4. Code of the EmployeeController class.

The controller is straightforward; it keeps the repository that was created as a global variable to be used below by the other listing and creation methods. Later, it’d be interesting to add the other equivalent CRUD operations. I’ll leave it as homework for you.

The views

Now to move on to the views. You’ll see that you already have some Razor view files there that can all be deleted. You won’t need any of them. Liquid views always end with the .liquid extension. Here, you’ll need four Liquid view files following this hierarchy:

– Employee

      – Create.liquid

      – Index.liquid

– _Layout.liquid

– _ViewStart.liquid

Make sure to create the same structure accordingly. Listing 5 shows the code that composes the Employee/Create.liquid file.

Listing 5. Code of the Create.liquid file.

This is basic Bootstrap HTML content. A single form that maps to the POST method created in the controller and a link that drives the user back to the index page. A similar template file could be used for the edition page, for example.

The Index.liquid file (shown in Listing 6), in turn, is a composition of a link to call the form just created and, second, the listing of all employee’s data into an HTML table.

Listing 6. Code of the Index.liquid file.

Look how Liquid deals with loops, specifically with a foreach. It’s very similar to other languages and close to a language that resembles React, for example. In other words, by using Liquid templates, you have a cleaner and more beautiful HTML setup.

Next, comes the code for the_Layout.liquid file. See it at Listing 7.

Listing 7. Code of the _Layout.liquid file.

In the code above, it is important to emphasize the {% renderbody%} tag. It indicates the point where the content of the views will be rendered in the template, working like Razor’s @RenderBody().

Note this snippet as well: <title>{{ ViewData['Title'] }}</title>. In it, you are using two keys. These keys are used to indicate objects to be rendered. In this way, when this template is processed, the content of ViewData['Title'] will be displayed in the generated HTML.

Finally, here you have the content of the last Liquid file, _ViewStart.liquid file:

It’s that simple! This tag is used to define the standard template used in the views of the current folder and all subfolders, functioning as a “master page”.

Testing time! To test the application, you just need to hit the ISS Express button, to the right of the Debug options or press the F5 button.

Summary

Liquid’s support for ASP.NET does not mean you should use it in all your applications. As stated in the beginning, Razor is a powerful tool, which should not be replaced unnecessarily.

Liquid is a more accessible template engine for people with little programming knowledge. When working on a project where the people who will be dealing with the templates have these characteristics, you should take a look at this template engine.