Skip to content

Engine

Micro rendering template engine

Examples

js
// 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

NameTypeDescription
[opts]TemplateOptsThe TemplateOpts to use
[readFormatter]functionThe function(string, readFormatOptions) that will return a formatted string for reading
data using the options.readFormatOptions from TemplateOpts as the formatting options. Typically reads are for HTML
minification and/or beautifying.
[writeFormatter]functionThe function(string, writeFormatOptions) that will return a formatted string for writting
data using the options.writeFormatOptions from TemplateOpts as the formatting options. Typically reads are for JS
minification and/or beautifying.
[log]ObjectThe log for handling logging output
[log.debug]functionA function that will accept debug level logging messages (i.e. debug('some message to log'))
[log.info]functionA function that will accept info level logging messages (i.e. info('some message to log'))
[log.warn]functionA function that will accept warning level logging messages (i.e. warn('some message to log'))
[log.error]functionA 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

NameTypeDescription
cachierCachierThe 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

NameTypeDescription
[content]String | BooleanThe 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]ObjectThe options sent for compilation (omit to use the options set on the Engine)
[params]URLSearchParamsAny URL search parmeters that will be passed when capturing the primary template and/or
context when needed. Parameters can be excluded from the invocation by replacing params with a callback (e.g.
compile(content, opts, callback)).
[legacyCallback]functionOptional callback style support for LEGACY-ONLY APIs:
compile(content, opts, (error, (ctx, opts, cb) => cb(error, results)) => {}) or omit to run via
await 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 rendering async function that returns a template result string based upon the provided context. The following arguments apply:
  1. {Object} context The context JSON that can be used as data during rendering
  2. {TemplateOpts} [renderOptions] The rendering options that will superceed any compile-time options
  3. {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 the options.readFormatOptions. The returned result should be a valid string.
  4. {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 the options.writeFormatOptions. The returned result should be a valid string.
  5. {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.legacyRenderOptionsTemplateOpts

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

NameTypeDescription
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

NameTypeDefaultDescription
nameStringThe name that uniquely identifies the template, partial or context
[params]URLSearchParamsAny parameters designated during Engine.registerPartial
[extension=options.defaultExtension]Stringoptions.defaultExtensionOptional override for a file extension designation
for the template, partial or context designated during Engine.registerPartial

Returns

engine.unregister(name)

Unregisters a template, partial or context from cache

Async: yes

Parameters

NameTypeDescription
nameStringThe 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

NameTypeDescription
[data]Array.<Object>The template, partials and/or context to register.
partials[].nameStringThe name that uniquely identifies the template, partial or context
[partials[].content]StringThe raw content that will be registered. Omit when read === true to read content from cache.
[partials[].params]URLSearchParamsThe URLSearchParams that will be passed during the content read
(ignored when content is specified).
[partials[].extension]StringOptional override for a file extension designated for a template, partial or context.
[read]BooleanWhen true, an attempt will be made to also Cachier.read the template, partials and context that
do not have a content property set.
[write]BooleanWhen true, an attempt will be made to also Cachier.write the template, partials and context that
have a content property set.

Returns

  • Object — An object that contains the registration results:

  • data The object that contains the template, partial fragments and/or context that have been registered

    • name The name that uniquely identifies the template, partial or context
    • content The raw content of the template, partial or context
    • extension The template file extension designation
    • params The URLSearchParams passed during the initial content read
    • fromRead A flag that indicates that the data was set from a read operation
    • overrideFromFileRead A flag that indicates if the passed partial content was overridden by content from a file read
  • dirs Present 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

NameTypeDefaultDescription
nameStringThe template name that uniquely identifies the template content
contentOrParamsString | URLSearchParamsEither the partial template content string to register or the
URLSearchParams that will be passed during the content read
[extension=options.defaultExtension]Stringoptions.defaultExtensionOptional override for a file extension designation for the partial

Returns

  • String — The partial content

engine.renderPartialGenerate()function

Returns

  • function — A reference safe async function 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

NameTypeDefaultDescription
nameStringThe 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

NameTypeDescription
funcfunctionA named function that has no external scope dependencies/closures other than those exposed
via templates during rendering

engine.clearCache([all])

Clears the underlying cache.

Async: yes

Parameters

NameTypeDescription
[all]BooleanOptional 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.cacheStatsObject

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.optionsTemplateOpts

Returns

  • TemplateOpts — The engine options

Released under the MIT License.