edge.js Template Engine
repository·6.x·Indexed 21 days ago
https://github.com/edge-js/edgeA modern, batteries-included template engine for Node.js featuring a JavaScript-like syntax. Version 6.5.1 provides capabilities for asynchronous and synchronous rendering via render(), renderSync(), and raw string rendering. It supports custom tags, plugins, global variables, and view directory mounting. The engine includes built-in tags for control flow, variable management, data structures, and template composition.
What's inside edge.js
- Edge is a modern, batteries-included template engine designed for Node.js. Its syntax is heavily inspired by JavaScript, making it intuitive for developers who are already familiar with the language. It is designed to be simple and powerful for rendering dynamic content.
Initialize the Edge template engine with the default instance
6.xThe
edgedefault export provides a pre-configured instance of theEdgeclass created viaEdge.create(). You can import this instance directly to start rendering templates without manual initialization.import edge from 'edge-js/edge'; // Use the default instance to render templates const html = await edge.render('hello {{name}}', { name: 'World' });Render raw template strings
6.xIf you have a template string that is not stored in a file, use
renderRaw()(asynchronous) orrenderRawSync()(synchronous). You can optionally provide atemplatePathto help with caching and error reporting.// Asynchronous raw rendering const html = await edge.renderRaw('<h1>{{ greeting }}</h1>', { greeting: 'Hello' }) // Synchronous raw rendering const htmlSync = edge.renderRawSync('<h1>{{ greeting }}</h1>', { greeting: 'Hello' })Register custom globals
6.xUse
global(name, value)to add variables or functions that are accessible in every template rendered by the Edge instance.edge.global('username', 'virk') edge.global('time', () => new Date().getTime())Use Edge template tags
6.xEdge provides a wide range of built-in tags for controlling template logic, such as control flow, variable assignment, and component management. These tags are exported with short aliases to allow for concise template syntax. Common categories include:
- Control Flow:
if,else,elseif,unless,each - Variable Management:
let,assign,inject - Data Structures:
pushTo,pushOnceTo,stack - Template Composition:
component,slot,include,includeIf - Execution & Debugging:
eval,debugger,newError
// Note: Usage occurs within Edge template strings or files. // Example conceptual usage: // @if (user.isAdmin) { // <p>Welcome, Admin!</p> // } @else { // <p>Welcome, User!</p> // } // @each (item in items) { // <li>{{ item.name }}</li> // } // @end- Control Flow:
Render templates using render() and renderSync()
6.xThe
Edgeinstance provides several methods to render templates. Userender()for asynchronous rendering (returns aPromise<string>) andrenderSync()for synchronous rendering (returns astring). Both methods accept atemplatePathand an optionalstateobject containing local variables for the template.// Asynchronous rendering const html = await edge.render('welcome', { greeting: 'Hello world' }) // Synchronous rendering const htmlSync = edge.renderSync('welcome', { greeting: 'Hello world' })Register in-memory templates
6.xYou can register templates directly in memory using
registerTemplate(templatePath, contents). This is useful for dynamic templates or those generated at runtime. UseremoveTemplate(templatePath)to clear them from the loader and compiler cache.edge.registerTemplate('button', { template: `<button class="{{ this.type || 'primary' }}"> @!yield($slots.main()) </button>`, }) // Usage in an Edge template: // @component('button', type = 'primary') // Get started // @endcomponentCreate a new Edge engine instance using Edge.create()
6.xTo create a custom instance of the template engine with specific configurations, use the
Edge.create()method from theEdgeclass.import { Edge } from 'edge-js/edge'; const edge = Edge.create();Initialize Edge with create()
6.xTo start using Edge, use the
Edge.create()static method. This creates a new instance of theEdgeclass with the provided configuration options. If no options are provided, it uses default settings.import Edge from 'edge.js' const edge = Edge.create({ cache: true })Use plugins to extend Edge
6.xPlugins can be registered using the
use(pluginFn, options)method. Plugins are executed just before a rendering operation occurs. By default, they run once, but you can make them recurring by passingoptions: { recurring: true }(or via the plugin's own logic).edge.use((edge, isFirstRun, options) => { // Plugin logic here }, { recurring: true })Register custom tags
6.xExtend Edge's functionality by registering custom tags using
registerTag(tag). A tag object must follow theTagContractand can include abootfunction to initialize the tag with template capabilities.edge.registerTag({ tagName: 'svg', block: false, seekable: true, compile (parser, buffer, token) { const fileName = token.properties.jsArg.trim() buffer.writeRaw(fs.readFileSync(__dirname, 'assets', `${fileName}.svg`), 'utf-8') } })Mount and unmount view directories
6.xYou can organize your templates into named disks using
mount(). This allows you to reference templates using adiskName::filenamesyntax. Useunmount()to remove a disk from the loader.import { join } from 'path' // Mount a directory to the 'admin' disk edge.mount('admin', join(__dirname, 'admin')) // Reference a template from the 'admin' disk const html = await edge.render('admin::filename') // Unmount the disk edge.unmount('admin')