Git Product home page Git Product logo

perfect-mustache's Introduction

Perfect-Mustache

Get Involed with Perfect!

Star Perfect On Github Stack Overflow Follow Perfect on Twitter Join the Perfect Slack

Swift 4.1 Platforms OS X | Linux License Apache PerfectlySoft Twitter Slack Status

Mustache template support for Perfect.

This package is designed to work along with Perfect. It provides Mustache template support for your server.

Quick Start

To start, add this project as a dependency in your Package.swift file.

.package(url: "https://github.com/PerfectlySoft/Perfect-Mustache.git", from: "3.0.0")

Then, add "PerfectMustache" to the list of dependencies for the target that will use PerfectMustache.

Example target configuration:

targets: [.target(name: "PerfectTemplate", dependencies: ["PerfectHTTPServer", "PerfectMustache"])]

Basic usage:

let map: [String:Any] = ["fullName":fullName, "uri":uri, "authToken":authToken]
let ctx = MustacheEvaluationContext(templatePath: emailTemplate, map: map)
let result = try ctx.formulateResponse(withCollector: MustacheEvaluationOutputCollector())

The following snippet illustrates how to use mustache templates in your URL handler. In this example, the template named "test.html" would be located in your server's web root directory.

{
	request, response in 
	let webRoot = request.documentRoot
	mustacheRequest(request: request, response: response, handler: TestHandler(), templatePath: webRoot + "/test.html")
}

The template page handler, which you would impliment, might look like the following.

struct TestHandler: MustachePageHandler { // all template handlers must inherit from PageHandler
	// This is the function which all handlers must impliment.
	// It is called by the system to allow the handler to return the set of values which will be used when populating the template.
	// - parameter context: The MustacheWebEvaluationContext which provides access to the HTTPRequest containing all the information pertaining to the request
	// - parameter collector: The MustacheEvaluationOutputCollector which can be used to adjust the template output. For example a `defaultEncodingFunc` could be installed to change how outgoing values are encoded.
	func extendValuesForResponse(context contxt: MustacheWebEvaluationContext, collector: MustacheEvaluationOutputCollector) {
		var values = MustacheEvaluationContext.MapType()
		values["value"] = "hello"
		/// etc.
		contxt.extendValues(with: values)
		do {
			try contxt.requestCompleted(withCollector: collector)
		} catch {
			let response = contxt.webResponse
			response.status = .internalServerError
			response.appendBody(string: "\(error)")
			response.completed()
		}
	}
}

Look at the UploadEnumerator example for a more concrete example.

Tag Support

This mustache template processor supports:

  • {{regularTags}}
  • {{{unencodedTags}}}
  • {{& unescapedTags}}
  • {{# sections}} ... {{/sections}}
  • {{^ invertedSections}} ... {{/invertedSections}}
  • {{! comments}}
  • {{> partials}}
  • lambdas

Partials

All files used for partials must be located in the same directory as the calling template. Additionally, all partial files must have the file extension of mustache but this extension must not be included in the partial tag itself. For example, to include the contents of the file foo.mustache you would use the tag {{> foo }}.

Encoding

By default, all encoded tags (i.e. regular tags) are HTML encoded and < & > entities will be escaped. In your handler you can manually set the MustacheEvaluationOutputCollector.defaultEncodingFunc function to perform whatever encoding you need. For example when outputting JSON data you would want to set this function to something like the following:

collector.defaultEncodingFunc = { 
	string in 
	return (try? string.jsonEncodedString()) ?? "bad string"
}

Lambdas

Functions can be added to the values dictionary. These will be executed and the results will be added to the template output. Such functions should have the following signature:

(tag: String, context: MustacheEvaluationContext) -> String

The tag parameter will be the tag name. For example the tag {{name}} would give you the value "name" for the tag parameter.

Further Documentation

For more information, please visit perfect.org.

perfect-mustache's People

Contributors

ericfromcanada avatar iamjono avatar kjessup avatar mmdock avatar rockfordwei avatar thislooksfun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.