Up and Running with Server Side Swift: Part 2 — Perfect Mustache
Ive wanted a basic, browser based todo list for a while. Something free of any distractions. Building this with Swift, and getting to know some of the libraries involved seemed like a great place to start.
This is a 4 part series outlining how to set up the project, getting started with routing, setting up the database and finally creating the model and controllers of our application. To see part 1 click here.
Introduction
Now that we have a web server up and running, serving us text, lets see if we can get it to serve up some HTML. We’ll also want to inject some values from our swift code into our HTML. To do this we’re going to use perfect Mustache.
Getting Mustache
We need to add Perfect Mustache to our list of project dependencies. So in Package.swift
add the following.
.package(url: “https://github.com/PerfectlySoft/Perfect-Mustache.git", from: “3.0.0”)
Remember to add PerfectMustache
to the list of target dependancies.
Back at our terminal, we’ll update our project with
swift package update
swift package generate-xcodeproj
To make sure everything is ok, add import PerfectMustache
to the list of imports in Main.swift
and build and run.
Adding HTML Files
We now need to add some HTML files to our project. Add a file, hello.html
to our webroot
directory and add some HTML.
The server needs a route for this new html, and in order for us to use Mustache, we need to create a type that conforms to the MustachePageHandler
protocol. This has one method that needs implimenting, func extendValuesForResponse(context contxt: MustacheWebEvaluationContext, collector: MustacheEvaluationOutputCollector)
This handles the data that will be used to fill in any of the mustache template.
The type also has a property that can be passed to the template to render.
Our Main.swift
will look something like this.
We’ve added a route for the URI /helloMustache
. The response and request are handled by a method called helloMustache(request: HTTPRequest, response: HTTPResponse)
. Here we call mustacheRequest
and pass in a value for name
in a variable of type MustacheEvaluationContext.MapType()
. This is just a typealias for [String:any]
.
Build and Run, navigate to localhost:8080/helloMustache
and you should see the HTML with the values passed in from your swift code. Pretty cool eh!
Next up…
So now our basic swift webserver is not only serving us just text, but serving us actual HTML files, and we are able to pass in some new computed values from our swift code. Next up, we’ll take a look at some database actions with postgrSQL and StORM. Click this link to see more.