Templating with DotLiquid

This guide will help you understand how to use DotLiquid to render dynamic pages.

Configuration

DotLiquid uses some config options which are passed when creating a new instance of App.

By default, DotLiquid will search for templates in the /resources folder and will search for partials templates in the /resources/partials folder.

C#
App(config => {
    config.ResourcesFolder = resourcesFolder          // resources path for DotLiquid (default is "/resources")
    config.PartialsFolder = partialsFolder          // partials folder for DotLiquid (default is "/partials")
})

To include these files in your build, you need to specify it in your project’s .csproj file:

XML
<ItemGroup> 
  <None Include="resources\**"> 
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> 
  </None> 
</ItemGroup>

Rendering a simple page

Inside of the /resources folder, let’s create a simple index.liquid file:

Liquid
<!doctype html>
<html lang="en">
  <body>
    <p>Hello {{ "World" | upcase }}!</p>
  </body>
</html>

Now let’s create a Bemol app that will display this page:

C#
using Bemol;

public class Program {
  public static void Main() {
    App app = new App().Start();
    app.Get("/", ctx => ctx.Render("/index.liquid");
  }
}

If everything worked, you should see a page displaying Hello WORLD!.

Using includes

If your website has many different pages, you might want them to share some code. This is possible with the use of the include tag. The include tag will add a liquid file located in the /resources/partials folder and prepended with an underscore.

Inside of the /resources folder, let’s modify our index.liquid file:

Liquid
{%- include 'header', title: "Hello World page" -%}

<p>Hello {{ "World" | upcase }}!</p>

{%- include 'footer' -%}

Then, inside the /resources/partials folder, we’ll add a _header.liquid file:

Liquid
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{{ title }}</title>
</head>
<body>

Also inside the /resources/partials folder, we’ll add a _footer.liquid file:

Liquid
  <p>This is the footer!</p>
</body>
</html>

If everything worked, you should see a page with the title Hello World page, and the content Hello WORLD!. This is the footer!.