When ever I try out a new web framework one of the first things I look at doing is setting up a template engine for html. So when I started playing with Suave this is exactly what I did.
Suave is a simple web development F# library providing a lightweight web server and a set of combinators to manipulate route flow and task composition
Using the template engine DotLiqud:
DotLiquid is a templating system ported to the .net framework from Ruby’s Liquid Markup.
I thought I’d share some simple examples of how to use DotLiquid with the F# web framework Suave. This post isn’t going to go into detail about how it works, I’ll save that for a later post, I just wanted to show some quick examples.
Without further ado here is the first example (you will need to install Suave and Suave.DotLiquid packages, using either nuget or paket).
As you can see it’s quite minimal.
On line 7 we tell DotLiquid where our templates live.
Then on line 9 and 10 we define the data or model we wish to inject into our template.
Next we define a simple index function which renders a template with the name of “index.html” (which is in the templates directory we defined earlier) and passes model “people” to it.
Then the final step is to start the webserver with the default config provided by Suave and set the routing. Here we state that any request to the root of the site (in this case http://localhost:8083) will return the results of the index function.
Here is a copy of the index template:
Nothing too exciting but you can see how we use DotLiquid to render information that we passed into the template.
You’ll notice that the href for each person points to a details page, that doesn’t currently exist so let’s create it.
Now we need to modify our existing code a little to support the details path.
First we define a details function on line 13 which takes in the name of person we wish to view the details for. This like the index function renders a page and passes a model to it, in this case the model is a person from the list of people where the name matches the name passed into the function.
Now because we have two paths (routes) we use a built in Suave function called “choose” which allows us to define multiple paths. We used “pathScan” instead of “path” because we want to pull out information from the url and pass this to our function.
And there you have it a simple “dynamic” website with templating.
If you’d like to learn more about Suave check out the following resources:
Suave – Suave homepage which contains examples and docs.
Suave Music Store – great starting point in creating a music store site using Suave.
Tomas Petricek’s blog – articles on Suave and much more.
Tamizhvendan S – articles on Suave (including a book) and F#