Engine
Micro rendering template engine
Examples
// Hapi.js example:
import Hapi from 'hapi';
import Vision from 'vision';
import { html as HtmlFrmt, js as JsFrmt } from 'js-beautify';
import Engine from 'templeo';
const econf = {
partialsURL: 'https://example.com', // partial reads from a server?
contextURL: 'https://example.com', // context read from a server?
partialsPath: 'views/partials', // file path to the partials
defaultExtension: 'html' // can be HTML, JSON, etc.
};
const cachier = new CachierFiles(econf, HtmlFrmt, JsFrmt);
const htmlEngine = new Engine(cachier);
// use the following instead if compiled templates don't need to be stored in files
// const htmlEngine = new Engine(econf, HtmlFrmt, JsFrmt);
const server = Hapi.Server({});
await server.register(Vision);
server.views({
compileMode: 'async',
relativeTo: '.',
path: 'views',
partialsPath: econf.partialsPath,
defaultExtension: econf.defaultExtension,
layoutPath: 'views/layout',
layout: true,
helpersPath: 'views/helpers',
engines: {
html: htmlEngine,
json: new JsonEngine()
}
});
// optionally set a partial function that can be accessed in the routes for
// instances where partials need to be generated, but not rendered to clients
server.app.htmlPartial = htmlEngine.genPartialFunc();
await server.start();
// it's a good practice to clear files after the server shuts down
server.events.on('stop', async () => {
await htmlEngine.clearCache();
});new Engine([opts], [readFormatter], [writeFormatter], [log])
Creates a template literal engine
Parameters
| Name | Type | Description |
|---|---|---|
| [opts] | TemplateOpts | The TemplateOpts to use |
| [readFormatter] | function | The function(string, readFormatOptions) that will return a formatted string for readingdata using the options.readFormatOptions from TemplateOpts as the formatting options. Typically reads are for HTMLminification and/or beautifying. |
| [writeFormatter] | function | The function(string, writeFormatOptions) that will return a formatted string for writtingdata using the options.writeFormatOptions from TemplateOpts as the formatting options. Typically reads are for JSminification and/or beautifying. |
| [log] | Object | The log for handling logging output |
| [log.debug] | function | A function that will accept debug level logging messages (i.e. debug('some message to log')) |
| [log.info] | function | A function that will accept info level logging messages (i.e. info('some message to log')) |
| [log.warn] | function | A function that will accept warning level logging messages (i.e. warn('some message to log')) |
| [log.error] | function | A function that will accept error level logging messages (i.e. error('some message to log')) |
Engine.create(cachier) ⇒ Engine
Creates a new Engine from a Cachier instance
Parameters
| Name | Type | Description |
|---|---|---|
| cachier | Cachier | The Cachier to use for persistence management |
Returns
Engine— The generated Engine
engine.compile([content], [opts], [params], [legacyCallback]) ⇒ function
Compiles a template and returns a function that renders the template results using the passed context object
Async: yes
Parameters
| Name | Type | Description |
|---|---|---|
| [content] | String | Boolean | The raw template content, true to read from cache before compilation.Omit to load the template content from cache when the returned rendering function is called. |
| [opts] | Object | The options sent for compilation (omit to use the options set on the Engine) |
| [params] | URLSearchParams | Any URL search parmeters that will be passed when capturing the primary template and/orcontext when needed. Parameters can be excluded from the invocation by replacing params with a callback (e.g.compile(content, opts, callback)). |
| [legacyCallback] | function | Optional callback style support for LEGACY-ONLY APIs: compile(content, opts, (error, (ctx, opts, cb) => cb(error, results)) => {}) or omit to run viaawait compile(content, opts). Omission will return the normal stand-alone renderer that can be serialized/deserialized.When a legacy callback function is specified, serialization/deserialization of the rendering function will not be possible! In legacy mode Engine.legacyRenderOptions will be used during any rendering call that does not pass rendering options or passes rendering options that does not contain any properties. |
Returns
function— The renderingasync functionthat returns a template result string based upon the provided context. The following arguments apply:
- {Object}
contextThe context JSON that can be used as data during rendering - {TemplateOpts}
[renderOptions]The rendering options that will superceed any compile-time options - {Function}
[readFormatter]The function that will format read partials during include discovery (if any). The formatting function takes 1 or 2 arguments with the first being the content that will be formatted and the second being theoptions.readFormatOptions. The returned result should be a valid string. - {Function}
[writeFormatter]The function that will format written sources during include discovery (if any). The formatting function takes 1 or 2 arguments with the first being the content that will be formatted and the second being theoptions.writeFormatOptions. The returned result should be a valid string. - {Object}
[sharedStore]An object used for in-memory storage space that can be shared between rendering functions. This ensures that updated data within a renderer execution will be retained between rendering calls from the same renderer or different renderers that are passed the same shared store.
engine.legacyRenderOptions ⇒ TemplateOpts
Returns
TemplateOpts— The LEGACY-ONLY API TemplateOpts to use when no rendering options are passed (or are empty) into the rendering function and a callback function is specified when calling Engine.compile See Engine.compile for more details.
engine.legacyRenderOptions
The LEGACY-ONLY API TemplateOpts to use when no rendering options are passed (or are empty) into the rendering function and a callback function is specified when calling Engine.compile
Parameters
| Name | Type | Description |
|---|---|---|
| opts | * | The options to set |
engine.getRegistered(name, [params], [extension=options.defaultExtension]) ⇒ Object
Retrieves a template, partial or context that resides in-memory.
Async: yes
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| name | String | The name that uniquely identifies the template, partial or context | |
| [params] | URLSearchParams | Any parameters designated during Engine.registerPartial | |
| [extension=options.defaultExtension] | String | options.defaultExtension | Optional override for a file extension designation for the template, partial or context designated during Engine.registerPartial |
Returns
Object— A copy of the generated data from Engine.registerPartial
engine.unregister(name)
Unregisters a template, partial or context from cache
Async: yes
Parameters
| Name | Type | Description |
|---|---|---|
| name | String | The name that uniquely identifies the template, partial or context |
engine.register([data], [read], [write]) ⇒ Object
Registers and caches the template, one or more partial templates and/or context JSON.
Async: yes
Parameters
| Name | Type | Description |
|---|---|---|
| [data] | Array.<Object> | The template, partials and/or context to register. |
| partials[].name | String | The name that uniquely identifies the template, partial or context |
| [partials[].content] | String | The raw content that will be registered. Omit when read === true to read content from cache. |
| [partials[].params] | URLSearchParams | The URLSearchParams that will be passed during the content read(ignored when content is specified). |
| [partials[].extension] | String | Optional override for a file extension designated for a template, partial or context. |
| [read] | Boolean | When true, an attempt will be made to also Cachier.read the template, partials and context thatdo not have a content property set. |
| [write] | Boolean | When true, an attempt will be made to also Cachier.write the template, partials and context thathave a content property set. |
Returns
Object— An object that contains the registration results:dataThe object that contains the template, partial fragments and/or context that have been registerednameThe name that uniquely identifies the template, partial or contextcontentThe raw content of the template, partial or contextextensionThe template file extension designationparamsThe URLSearchParams passed during the initial content readfromReadA flag that indicates that the data was set from a read operationoverrideFromFileReadA flag that indicates if the passed partial content was overridden by content from a file read
dirsPresent only when file system back-end is used. Contains the directories/sub-directories that were created
engine.registerPartial(name, contentOrParams, [extension=options.defaultExtension]) ⇒ String
Registers and stores a partial template in-memory. Use Engine.register to write/persist partials to cache (Cachier)
Async: yes
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| name | String | The template name that uniquely identifies the template content | |
| contentOrParams | String | URLSearchParams | Either the partial template content string to register or theURLSearchParams that will be passed during the content read | |
| [extension=options.defaultExtension] | String | options.defaultExtension | Optional override for a file extension designation for the partial |
Returns
String— The partial content
engine.renderPartialGenerate() ⇒ function
Returns
function— A reference safeasyncfunction to Engine.renderPartial that can be safely passed into other functions
engine.renderPartial(name, [context={}]) ⇒ String
On-Demand compilation of a registered templates
Async: yes
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| name | String | The name of the registered tempalte | |
| [context={}] | Object | {} | The object that contains contextual data used by the template |
Returns
String— The rendered template
engine.registerHelper(func)
Registers a directive function that can be used within template interpolations
Parameters
| Name | Type | Description |
|---|---|---|
| func | function | A named function that has no external scope dependencies/closures other than those exposedvia templates during rendering |
engine.clearCache([all])
Clears the underlying cache.
Async: yes
Parameters
| Name | Type | Description |
|---|---|---|
| [all] | Boolean | Optional cache-specific scope flag. When omitted, the configured cache's default is used. |
engine.clearMemory() ⇒ Promise.<*>
Clears only in-memory template content and compiled renderers.
Returns
Promise.<*>— The cache cleanup result.
engine.startWatching() ⇒ Promise.<Number>
Starts native file-system watchers when supported by the configured cache.
Returns
Promise.<Number>— The number of active watchers.
engine.stopWatching() ⇒ Promise.<Number>
Stops native file-system watchers when supported by the configured cache.
Returns
Promise.<Number>— The number of closed watchers.
engine.reconcileWatching() ⇒ Promise.<Number>
Reconciles native file-system watchers with the current partial tree when supported by the configured cache.
Returns
Promise.<Number>— The number of files discovered during reconciliation.
engine.close() ⇒ Promise.<*>
Releases cache resources without deleting persistent cache files.
Returns
Promise.<*>— The close result.
engine.cacheStats ⇒ Object
Returns
Object— Cache activity and current cache-size statistics.
engine.resetCacheStats() ⇒ Object
Resets cumulative cache counters while retaining current entry and byte totals.
Returns
Object— The reset statistics.
engine.options ⇒ TemplateOpts
Returns
TemplateOpts— The engine options