refactor: Introducing Environments

This commit is contained in:
Kyle Fuller
2016-12-01 00:17:04 +00:00
parent 2be672c6a5
commit 9e2a061795
27 changed files with 289 additions and 91 deletions

View File

@@ -6,12 +6,6 @@ template. Its somewhat like a dictionary, however you can push and pop to
scope variables. So that means that when iterating over a for loop, you can
push a new scope into the context to store any variables local to the scope.
You can initialise a ``Context`` with a ``Dictionary``.
.. code-block:: swift
Context(dictionary: [String: Any]? = nil)
API
----

43
docs/api/environment.rst Normal file
View File

@@ -0,0 +1,43 @@
Environment
===========
An environment contains shared configuration such as custom filters and tags
along with template loaders.
.. code-block:: swift
let environment = Environment()
You can optionally provide a loader or namespace when creating an environment:
.. code-block:: swift
let environment = Environment(loader: ..., namespace: ...)
Rendering a Template
--------------------
Environment providences coninience methods to render a template either from a
string or a template loader.
.. code-block:: swift
let template = "Hello {{ name }}"
let context = ["name": "Kyle"]
let rendered = environment.render(templateString: template, context: context)
Rendering a template from the configured loader:
.. code-block:: swift
let context = ["name": "Kyle"]
let rendered = environment.render(templateName: "example.html", context: context)
Loading a Template
------------------
Environment provides an API to load a template from the configured loader.
.. code-block:: swift
let template = try environment.loadTemplate(name: "example.html")

38
docs/api/loader.rst Normal file
View File

@@ -0,0 +1,38 @@
Loader
======
Loaders are responsible for loading templates from a resource such as the file
system.
Stencil provides a ``FileSytemLoader`` which allows you to load a template
directly from the file system.
``Loader`` is a protocol, so you can implement your own compatible loaders. You
will need to implement a ``loadTemplate`` method to load the template,
throwing a ``TemplateDoesNotExist`` when the template is not found.
.. code-block:: swift
class ExampleMemoryLoader: Loader {
func loadTemplate(name: String, environment: Environment) throws -> Template {
if name == "index.html" {
return Template(templateString: "Hello", environment: environment)
}
throw TemplateDoesNotExist()
}
}
FileSystemLoader
----------------
Loads templates from the file system. This loader can find templates in folders
on the file system.
.. code-block:: swift
FileSystemLoader(paths: ["./templates"])
.. code-block:: swift
FileSystemLoader(bundle: [Bundle.main])