United Kingdom: +44 (0)208 088 8978

Fue – a server-side HTML templating library

In this week's post, Jaz takes a look at Fue, an F# library for working with HTML templates on the server.

We're hiring Software Developers

Click here to find out more

Fue is a library which can be used to render HTML - the idea being that it is very lightweight in a similar vein to Razor, but unlike Razor it has some features which are aimed specifically at F# users.

In order to play around with Fue, I set up a new project using the Giraffe template, added Fue from Nuget, then replaced the existing view with one created using Fue.

Overview

The general method for rendering a page using Fue is simple

  1. Define your HTML skeleton
  2. Add templated sections using triple curly-braces, e.g.: {{{ favouriteFood }}}
  3. Add control flow using attributes, e.g.: <p fs-if="willRainToday">Looks like rain!</p>
  4. Feed values, and the template, into Fue!

Like so:

init
|> add "favouriteFood" "Chocolate cake"
|> add "willRainToday" todaysForecast = Rain
|> fromText template
|> htmlString

Note that the final line - htmlString - is a function from Giraffe, used to return raw HTML.

Control attributes

When there is content which only needs to be rendered under certain conditions, we can use fs-if, and optionally also fs-else

For example:

<p fs-if="willRainToday">Looks like rain!</p>
<p fs-else>No rain today!</p>

Or, if the value is a discriminated union, we can use fs-du and fs-case:

type WeatherForecast =
    | Sun
    | Rain
    | Snow

...

<p fs-du="weatherForecast" fs-case="Sun">Don't forget your shades</p>
<p fs-du="weatherForecast" fs-case="Rain">Bring an umbrella</p>
<p fs-du="weatherForecast" fs-case="Snow">Wrap up warm</p>

We can even pull values out of the DU cases:

type User =
    | Anonymous
    | LoggedIn of string

...

<h1 fs-du="user" fs-case="Anonymous">Hello there, whoever you are!</h1>
<h1 fs-du="user" fs-case="LoggedIn(name)">Welcome back, {{{name}}}!</h1>

And if we have a collection which can be iterated over, we can use fs-for:

<div fs-for="movie in movies">
    <h2>{{{movie.Title}}} ({{{movie.ReleaseYear}}})</h2>
    <h3>Director: {{{movie.Director}}}</h3>
</div>

Takeaway

The features we have looked at in this post are just a sample; there are other useful things included in Fue which I have not covered here such as implicitly created variables (e.g. $index when inside a fs-for tag), record support, and in-template piping.

Due to the manner in which values are provided to the template - i.e. in combination with a string - there is less type safety than some other F# templating libraries, so personally I would avoid using it for very complex HTML rendering scenarios. That said, Fue is refreshingly simple, quick to set up, and delivers on its stated goal of server-side HTML rendering with support for F# constructs such as DUs.

If you are looking for something which is lightweight and simple to use then perhaps give it a try.