Search code examples
kitura

Find nill on rendering a response


I'm using Stencil. In the method below fails as the marked line comes back nil. This is straight from Paul Hudson's Kitura book (page 208). I have the stencil file in place and everything looks cool.

I've imported KituraStencil added the template engine (router.add(templateEngine: StencilTemplateEngine())). I am using the same function in my "/" route and it works just fine.

HeliumLogger only reports..[2017-01-02T05:17:45.534Z] [VERBOSE] [HTTPIncomingMessage.swift:335 onHeadersComplete(method:versionMajor:versionMinor:)] HTTP request from=172.17.0.1; proto=http;

Any ideas where to start?

router.get("/forum/:forumid") {
request, response, next in

guard let forumID = request.parameters["forumid"] else {
    send(error: "Missing forum ID", code: .badRequest, to: response)
    return
}

database.retrieve(forumID) { forum, error in
    if let error = error {
        send(error: error.localizedDescription, code: .notFound, to: response)
    } else if let forum = forum {
        database.queryByView("forum_posts", ofDesign: "forum", usingParameters: [.keys([forumID as Database.KeyType]), .descending(true)]) { messages, error in
            defer { next() }

            if let error = error {
                send(error: error.localizedDescription, code: .internalServerError, to: response)
            } else if let messages = messages {
                var pageContext = context(for: request)
                pageContext["forum_id"] = forum["_id"].stringValue
                pageContext["forum_name"] = forum["name"].stringValue
                pageContext["messages"] = messages["rows"].arrayObject


                //THIS LINE RETURNS Nil
                _ = try? response.render("forum", context: pageContext)

            }
        }
    }
}

}


Solution

  • You have to add StencilTemplateEngine to your router. E.g.:

    import KituraStencil
    
    router.setDefault(templateEngine: StencilTemplateEngine())
    

    or

    import KituraStencil
    
    router.add(templateEngine: StencilTemplateEngine())