Creating Web Pages with Vapor and Swift

This is Part 2 of an ongoing series on Getting Started with Vapor

For this tutorial, we’re going to take what we learned in Part 1 and create some web pages using Vapor’s templating system Leaf. First, let’s talk about what is Leaf. Leaf is a template engine designed to allow us to dynamically display information. Imagine you wanted to create a HTML page that displayed information specific to your current user, you wouldn’t want to have to create new pages for each individual user. With templates, we are able to reuse our code for multiple scenarios. There are several other templating systems we can use such as Mustache and Stencil but as Leaf is built with Swift we will be using it for this tutorial.

First, let’s begin by generating a new vapor project.

Step 1 — Generate a new Vapor project

Open your terminal and enter vapor new hellopages.

Step 2 — Generate a .xcodeproj project file

In terminal enter cd hellopages && vapor xcode. This will take us into the hellopage folder and run the vapor command to generate the project file. We always want to generate Xcode project files since this gives us access to Xcode’s error checking and code completion which makes coding with Swift significantly easier.

Step 3 — Create a new route for our new web page

First, open the main.swift file and create a route below the first route. Enter the following code right below the first route.

This creates a GET request to the route hello. If we were to run this and navigate to localhost:8080/hello using a browser we would see “hello”.

To create a web page in vapor, we need to change the response to our route. Change the return of the closure to the following

This line tells Vapor to look for a leaf template named hello.leaf and present it to the user. In case you’re wondering where is the hello.leaf file we haven’t created it yet.

Your main.swift file should look like this by now.

Step 4 — Create the hello page.

To create the hello page we will be creating a hello.leaf file. The .leaf extension is excluded from line 12 above since Leaf is the default templating engine used with Vapor. Template files must be placed in the Resources/Views folder.

Now let’s create the file. Right Click on Views and Click New File. Call this file hello.leaf. In this file enter the following code:

You will immediately notice that copying & pasting this code or even writing it out in Xcode doesn’t come with the usual syntax highlighting or indentation we are accustomed to. You can actually set Xcode’s highlighting to HTML for that file. Even though Xcode is built for Swift and Objective C it can be used as an IDE for other languages. You can find this option under Editor -> Syntax Highlighting -> HTML

By using the tab button I can adjust the lines slightly to produce the following.

Now go ahead and hit Cmd + R and open your browser to localhost:8080.

Step 5 — Add some dynamic content

Now let’s take this a little further and send some information from our droplet to our leaf template. Head back to main.swift and change your helloworld route to the following.

You will notice that the return here has been changed. We still use the same hello.leaf file but now we’re passing it what looks like a dictionary

Head back over to your hello.leaf file and change your file to resemble the following:

By using the #(greeting) syntax we are able to pass the variable from our return try drop.view.make(“hello”, [“greeting”: “World”]) to our leaf template.

Let’s try adding an array to our route and displaying its contents on the web page with <li></li> tags

Change the contents of your helloworld route to the following:

Here we have added an array called greetings that has the word “World” in Spanish, French and German. In our return, we have added a new key and value pair to our dictionary. You will notice that we call the function makeNode() on the greetings array. This function allows us to use our data types on the web pages. Arrays and Dictionaries already have this function built in thanks to Vapor’s extensions. Thankfully in case you ever forget to call makeNode() the compiler will graciously remind you.

In your hello.leaf file change your code to the following :

Here we have added the leaf tag #loop() which as its name suggests helps us loop through a collection. In #loop() we are calling on the worlds key we defined in our route and also passing in a name for each item in our collection i.e world. This should be very familiar to you in that it resembles the way Swift developers create for in loops. Now that we have a name to represent each item in the array we can use the #() tag to display each item on the webpage.

There are several other tags included with leaf such as the #if() and the #raw(). You can find the full listing in the Vapor Documentation on Leaf

Step 6 — Create a page template

To make our code more reusable, we wouldn’t want to have to include the following every time you create a new .leaf file.

If you look at the base.leaf you will notice #import(“head”) and #import(“body”). These two lines allow us to dynamically include code from other .leaf files. We can now update our hello.leaf file to take advantage of the templating available to them. Change the hello.leaf file to the following:

At the top, we use the extend() tag to indicate which .leaf file we want to include as our template. The string included between the parentheses have to match the exact name of the .leaf file. The #export() tag is used to include the content you want to display within the template. The string included in the #export() tag must match the string included in the #import() in the .leaf file you want to include the content in. This technique can help you reuse code and also provide consistent layouts across your web page.

Voila! We’ve created a webpage with Leaf templates. Now it’s your turn to take what you learned from Part 1 and create some more. Good Luck!

Getting started with Vapor

Swift on the Server

Last year at WWDC, Apple showed off the concept of server-side-swift utilizing IBM’s Kitura framework. The concept of using Swift on the server has taken the entire Swift community by storm and has lead to the advent of several other frameworks such as Vapor, Zewo and Perfect.

Why do we need Swift on the server?

For many iOS developers, one of the biggest hurdles in building apps has been the difficulty finding someone to build a backend for their app. Many developers have come up with ideas for applications but became stumped by the question of “Where do I store my data?” Some have had the fortune of working closely with friends who are web developers, and some have taught themselves Ruby on Rails or Node.js to actualize their dreams themselves. Some have even opted to utilize Backend-as-a-Service platforms (BAAS) such as Parse and Firebase. Parse was originally the go-to BAAS until Facebook purchased it, and then shortly after announced that it was shutting down.

With the development of server-side-swift frameworks, iOS developers now have the ability to create websites and app backends using the very same language they have become proficient using. Even someone relatively new to Swift can easily create their own website using the language. For this tutorial we will be using Vapor, as it is the easiest to get started with and has a rapidly growing community.

Let’s get started

Step 1 – Check if your computer is compatible with Vapor

First, you need to ensure your computer is compatible with Vapor. You should have at least Xcode 8 and Swift 3 installed.

Run the following to see if your computer is compatible.


How to see if your computer is compatible with Vapor

Once you confirm that your computer is compatible you must now install the Vapor toolbox.

Step 2 – Install the Vapor Toolbox


Installing the Vapor toolbox

The Vapor toolbox is useful since it provides you with a variety of nifty terminal commands to help you manage projects.

Step 3 — Create a new Vapor App

Let’s use the Vapor toolbox to generate our very own Vapor app. Go to Terminal and type the following:


Creating a new Vapor Project

Now that we have generated a new project called helloSwift, we can go into this directory using cd helloSwift.

Open this folder in Finder and take a look at its contents,

The main.swift highlighted in the image above is where we will be working for this tutorial. Before we proceed, you may have noticed there is no .xcodeproj, so how do we use Xcode to work with these files? It is totally okay to proceed using a text editor such as Sublime or Atom, but I would highly recommend using Xcode since it comes with its built-in code completion and compile time error checking. But the question remains, how do we open this folder without a .xcodeproj file? Yet again, Vapor comes in and simplifies this project.

Step 4 — Generate an Xcode project file

Run the following to create an Xcode project.


Using vapor to create an Xcode project

Now that you have your Xcode project open scroll down to the main.swift file. It can be found under the Sources group. -Sources/App/main.swift

Once you have found the main.swift file, you will want to run your project. Before hitting the run button we need to change the target of our application from helloSwift to App.

Now hit the Run button or Cmd + R to see your project run.

Once your program is finished building and has started running, you will the following message in your console.


Server running on 0.0.0.8080

The last line of the console message is letting you know that your server project is running on 0.0.0.0:8080 which is sometimes known as localhost. If you copy and paste it into the address bar in your favorite web browser you will see Vapor up and running. 0.0.0.0 is the IP address your app is running on, which signifies your local computer. :8080 signifies the port that your app is running on. You may also type in localhost:8080 and it will take you to the same page.

Hurray! Your very first Swift on the Server project is running. You are now a web developer! Okay not exactly but at least we’re on the road to there.

Now that we have gotten our server running let’s add some routes to our website.

Step 5 — Create your own custom routes

Imagine for a moment that a user would like to go to 0.0.0.0:8080/helloswift and is expecting to see a message from the server saying “Hello Swift”. How would we go about doing this? Head back to your main.swif and add the following lines under your first route in your main.swift file. (This file should come before the drop.run()line)

  1. This adds a GET route at localhost:8080/helloswift. The closure produces always produces a variable, which I highly recommend naming request. This request variable is of the Request type that has been provided to us by Vapor. This variable makes it easy for us to query information from the user such as data or parameters. We will not be going further into this for this tutorial but in future parts we will be.
  2. This is the response sent to the user once the navigate to our webpage in their browser. Our response is simply the returned string “Hello Swift”

Your code should look something like this now.

Let’s break this down for a second. When a user goes to localhost:8080/helloswift, this is the user making a GET request to our website at the route helloswift Therefore on line 11, we handle a get request to the string value “helloswift”. Once a user request is sent to this route we return the string “Hello Swift” to our user which is then displayed in the browser. Lets hit Cmd+ R and see it in our browser.

Okay so this is pretty simple let’s try doing something more interesting. Let’s see if we can add a route where a user can add their name and the respective message is Hello *Insert Name*. For example, if we go to localhost:8080/hello/johann we should see Hello johann . We first need to create a new GET route to hello that takes a String. Below your last route add the following lines.

  1. This adds a GET route at localhost:8080/hello/*someString* You should notice that we have included a new variable in the request closure called name The name variable corresponds to the String.self value. If we navigate in our browser to localhost:8080/hello/learn, the value of name becomes learn
  2. Now that name has a value we can return a response to the user that includes its value .

Now lets hit Cmd + R and see it run in our browser

Voila! We’ve created a website with a two routes using Swift on the Server. Now it’s your turn to try creating a few more routes using Swift. Good Luck!

Stay tuned for Part 2 of this Vapor series.