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

Kitura

Docs Build Status - Master macOS Linux Apache 2 Slack Status

Kitura-MustacheTemplateEngine

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

Summary

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

Mustache Template File

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

Mustache manual provides documentation and examples on how to write a Mustache template File.

By default the Kitura Router will look in the Views folder for Mustache template files with the extension .mustache.

Example

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

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

<ServerRepositoryName>
├── Package.swift
├── Sources
│    └── Application
│         └── Application.swift
└── Views
    └── Example.mustache

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

Package.swift

Application.swift

Inside the Application.swift file, add the following code to render the Example.mustache template file on the "/winner" route:

import KituraMustache

Add the following code inside the postInit() function:

router.add(templateEngine: MustacheTemplateEngine())
router.get("/winner") { _, response, next in
    let  winnings = 10000.0
    let context: [String:Any] =
        ["name" : "Joe Bloggs", "winnings": winnings, "taxed_winnings": winnings * 0.6, "taxable" : true]
    try response.render("Example.mustache", context: context)
    response.status(.OK)
    next()
}

Example.mustache

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

<html>
    Hello {{name}}!
    You have just won {{winnings}} dollars!
    {{#taxable}}
        Well, {{taxed_winnings}} dollars, after taxes.
    {{/taxable}}
</html>

This example is adapted from the Mustache manual code to congratulate the winner of a contest.

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

License

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