Skip to content

index

templeo

Micro rendering template engine

Example

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();
});

templeo~Engine

Kind: inner class of templeo

new Engine([opts], [readFormatter], [writeFormatter], [log])

Creates a template literal engine

ParamTypeDescription
[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.legacyRenderOptions ⇒ TemplateOpts

Kind: instance property of Engine
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

Kind: instance property of Engine

ParamTypeDescription
opts\*The options to set

engine.options ⇒ TemplateOpts

Kind: instance property of Engine
Returns: TemplateOpts - The engine options

engine.compile([content], [opts], [params], [legacyCallback]) ⇒ function

Compiles a template and returns a function that renders the template results using the passed context object

Kind: instance method of Engine
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.
ParamTypeDescription
[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.

engine.getRegistered(name, [params], [extension]) ⇒ Object

Retrieves a template, partial or context that resides in-memory.

Kind: instance method of Engine
Returns: Object - A copy of the generated data from Engine.registerPartial

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

engine.unregister(name)

Unregisters a template, partial or context from cache

Kind: instance method of Engine

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

Kind: instance method of Engine
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
ParamTypeDescription
[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.

engine.registerPartial(name, contentOrParams, [extension]) ⇒ String

Registers and stores a partial template in-memory. Use Engine.register to write/persist partials to cache (Cachier)

Kind: instance method of Engine
Returns: String - The partial content

ParamTypeDefaultDescription
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]Stringoptions.defaultExtensionOptional override for a file extension designation for the partial

engine.renderPartialGenerate() ⇒ function

Kind: instance method of Engine
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

Kind: instance method of Engine
Returns: String - The rendered template

ParamTypeDefaultDescription
nameStringThe name of the registered tempalte
[context]Object{}The object that contains contextual data used by the template

engine.registerHelper(func)

Registers a directive function that can be used within template interpolations

Kind: instance method of Engine

ParamTypeDescription
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

Kind: instance method of Engine

ParamTypeDefaultDescription
[all]Booleanfalsetrue to clear ALL unassociated cache instances when possible as well as any partials that have been registered

Engine.create(cachier) ⇒ Engine

Creates a new Engine from a Cachier instance

Kind: static method of Engine
Returns: Engine - The generated Engine

ParamTypeDescription
cachierCachierThe Cachier to use for persistence management

Released under the MIT License.