Swiftpack.co - Package - IBM-Swift/Kitura-StencilTemplateEngine


Docs Build Status - Master macOS Linux Apache 2 Slack Status


A templating engine for Kitura that uses Stencil-based templates.


Kitura-StencilTemplateEngine is a plugin for Kitura Template Engine for using Stencil with the Kitura server framework. This makes it easy to use Stencil templating, with a Kitura server, to create an HTML page with integrated Swift variables.

Stencil Template File

The template file is basically HTML with gaps where we can insert code and variables. Stencil is a templating language used to write a template file and Kitura-StencilTemplateEngine can use any standard Stencil template.

The Stencil user guide provides documentation and examples on how to write a Stencil template File.

The Kitura router, by default, will look in the Views folder for Stencil template files, that is files with the extension .stencil.


The following example takes a server generated using kitura init and modifies it to serve Stencil-formatted text from a .stencil file.

The files which will be edited in this example, are structured as follows:

├── Package.swift
├── Sources
│    └── Application
│         └── Application.swift
└── Views
     └── Example.stencil

The Views folder and Example.stencil file will be created later on in this example, since they are not initialized by kitura init.



Inside the Application.swift file, add the following code to render the Example.stencil template file on the "/articles" route.

import KituraStencil

Add the following code inside the postInit() function:

router.add(templateEngine: StencilTemplateEngine())
router.get("/articles") { _, response, next in
var context: [String: [[String:Any]]] =
        "articles": [
            ["title" : "Using Stencil with Swift", "author" : "IBM Swift"],
            ["title" : "Server-Side Swift with Kitura", "author" : "Kitura"],
    try response.render("Example.stencil", context: context)


Create the Views folder and put the following Stencil template code into a file called Example.stencil:

    There are {{ articles.count }} articles. <br />

    {% for article in articles %}
        - {{ article.title }} written by {{ article.author }}. <br />
    {% endfor %}

This example is adapted from the Stencil user guide code. It will display the number of articles followed by a list of the articles and their authors.

Run the application and once the server is running, go to http://localhost:8080/articles to view the rendered Stencil template.


This library is licensed under Apache 2.0. Full license text is available in LICENSE.