1.0.1 • Published 6 years ago

nucly-template v1.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
6 years ago

nucly-template

npm npm Travis

Extensible EJS like template engine

Installation

npm i nucly-template

Template Syntax

<% if (someItem) { %>
	<h3><%= someItem.title %></h3>
<% } %>

Tags

  • <% some.code(); %> Execute code
  • <%= value %> Escaped output
  • <%- value %> Unescaped output
  • <%# ... %> Comment
  • <%% Outputs <% (unescaped)

Usage

const template = require('nucly-template');

// Example:
const html = template.compile('<h1><%= message %></h1>')({
	message: 'Hello World!'
});
// html is: <h1>Hello World!</h1>

Compile

const render = template.compile(code, options, context);
  • code - The template code.
  • options - An object with the following options: + async - True, to compile to an async function. Default is false + useWith - True, to use with for accessing locals & the context. Default is true + pre - Javascript code to execute before the actual template starts rendering. + syntax - An object that defines a different syntax as explained below.
  • context The context object. Default is {}
  • returns the render function for the template.

Render

const html = render(locals);

// For async templates the render function returns a promise:
const html = await render(locals);
  • locals - An object with locals. Default is {}
  • returns html code or a promise that resolves to the html code if the template is async.

Accessing locals & context

If options.useWith was truthy, all properties from the locals or context object are accessible as they were globals. If not they must be accessed by using the locals or context object directly. Also properties from the locals object will override properties from the context object.

Customizing syntax

When compiling a template, pass a syntax option which has the following default values:

const syntax = {
	open: '<%', // Basic open tag.
	close: '%>', // Baseic close tag.

	// The following must be unique & must have a length of 1:
	write: '=', // Specifies the = in <%=
	writeUnescaped: '-', // Specifies the - in <%-
	comment: '#', // Specifies the # in <%#
	escape: '%' // Specifies the % in <%%
};

Keep in mind that the syntax configuration is not checked against invalidity and wrong configuration may lead to unexpected errors.

Running Tests

After cloning the repository & installing dependencies:

# Assert that everything is fine
npm test

# Run tests & watch for changes:
npm run test:dev

Note, that there should be no linter warnings at all.

1.0.1

6 years ago

1.0.0

6 years ago