edge.js Template Engine

repository·6.x·Indexed 21 days ago

https://github.com/edge-js/edge

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

Tokens
2.3K
Snippets
13
Records
17
Agent score
73%

What's inside edge.js

  1. What is Edge

    6.x
    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.
  2. Initialize the Edge template engine with the default instance

    6.x

    The edge default export provides a pre-configured instance of the Edge class created via Edge.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' });
  3. Render raw template strings

    6.x

    If you have a template string that is not stored in a file, use renderRaw() (asynchronous) or renderRawSync() (synchronous). You can optionally provide a templatePath to 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' })
  4. Use Edge template tags

    6.x

    Edge 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
  5. Render templates using render() and renderSync()

    6.x

    The Edge instance provides several methods to render templates. Use render() for asynchronous rendering (returns a Promise<string>) and renderSync() for synchronous rendering (returns a string). Both methods accept a templatePath and an optional state object 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' })
  6. Register in-memory templates

    6.x

    You can register templates directly in memory using registerTemplate(templatePath, contents). This is useful for dynamic templates or those generated at runtime. Use removeTemplate(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
    // @endcomponent
  7. Create a new Edge engine instance using Edge.create()

    6.x

    To create a custom instance of the template engine with specific configurations, use the Edge.create() method from the Edge class.

    import { Edge } from 'edge-js/edge';
    
    const edge = Edge.create();
  8. Initialize Edge with create()

    6.x

    To start using Edge, use the Edge.create() static method. This creates a new instance of the Edge class 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 })
  9. Use plugins to extend Edge

    6.x

    Plugins 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 passing options: { recurring: true } (or via the plugin's own logic).

    edge.use((edge, isFirstRun, options) => {
      // Plugin logic here
    }, { recurring: true })
  10. Register custom tags

    6.x

    Extend Edge's functionality by registering custom tags using registerTag(tag). A tag object must follow the TagContract and can include a boot function 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')
      }
    })
  11. Mount and unmount view directories

    6.x

    You can organize your templates into named disks using mount(). This allows you to reference templates using a diskName::filename syntax. Use unmount() 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')