Eta Documentation

repository·main·Indexed 23 days ago

https://github.com/bgub/eta

A lightweight, high-performance embedded JavaScript templating engine for Node.js, Deno, and the browser. Eta features a small footprint (~3.5 KB minzipped), zero dependencies, and supports both synchronous and asynchronous rendering. It provides a flexible configuration via EtaConfig for interpolation, tags, security filtering, and whitespace control, and includes a robust error reporting system with visual context for parse and runtime errors.

Tokens
5K
Snippets
8
Records
25
Agent score
82%

What's inside eta

  1. Get started with Eta templating

    main

    To use Eta, follow these steps:

    1. Create a template file (e.g., templates/simple.eta) using Eta's syntax. Variables are accessed via the it object.
    2. Import the Eta class in your JavaScript/TypeScript file.
    3. Initialize an Eta instance, optionally providing a views configuration to specify the directory where your templates are located.
    4. Use the .render() method to compile the template with a data object.
  2. Understand Eta error reporting and context

    main

    Eta provides enhanced error messages that include visual context to help you locate exactly where a template failed.

    Parse Errors

    When a parsing error occurs, the error message includes the line number, column number, and a visual pointer (^) to the specific character in the template string that caused the issue.

    Runtime Errors

    When a runtime error occurs (such as a ReferenceError inside a template), Eta wraps the original error in an EtaRuntimeError. This error includes:

    • The filename and line number.
    • A code snippet showing the lines surrounding the error (3 lines before and after).
    • A visual indicator (>>) pointing to the exact line where the error occurred.
    • The original error's message and its cause property.
  3. Integrate Eta with Webpack

    main

    While there is no official Webpack integration, you can use html-loader with a custom preprocessor to render Eta templates during the build process.

    {
      loader: 'html-loader',
      options: {
        preprocessor(content, loaderContext) {
          return eta.render(content, {}, { filename: loaderContext.resourcePath });
        },
      },
    }
  4. Configure Eta via EtaConfig

    main

    The EtaConfig interface defines the global configuration for the Eta template engine. You can use these settings to control how templates are parsed, how data is interpolated, and how whitespace is handled.

    Key configuration areas include:

    • Interpolation & Tags: Customize delimiters using tags (default ['<%', '%>']) or specific prefixes for execution (parse.exec), interpolation (parse.interpolate), and raw interpolation (parse.raw).
    • Data Handling: Control how data is accessed via varName (default it) and whether to use the with statement via useWith.
    • Security & Filtering: Enable automatic XML escaping with autoEscape and automatic filtering with autoFilter. You can provide custom logic via escapeFunction and filterFunction.
    • Whitespace Control: Use autoTrim to manage whitespace (options: 'nl', 'slurp', or false) and rmWhitespace to remove empty lines.
    • Template Management: Set a template directory with views and a defaultExtension (default .eta).
    • Plugins: Extend Eta functionality using the plugins array, which allows processing template strings, ASTs, or function strings.
  5. Configure tsdown build settings

    main

    Use defineConfig from tsdown to specify build configurations for one or more entry points. The configuration accepts an array of objects, allowing you to define different build targets (e.g., Node.js vs. Browser) within the same project.

    Available configuration options per entry point:

    • entry: An array of strings representing the input files.
    • format: An array of output formats (e.g., "esm", "cjs").
    • platform: The target environment (e.g., "node", "browser").
    • dts: Boolean to enable/disable TypeScript declaration generation.
    • sourcemap: Boolean to enable/disable sourcemap generation.
    • minify: Boolean to enable/disable code minification.
    import { defineConfig } from "tsdown";
    
    export default defineConfig([
      {
        entry: ["./src/index.ts"],
        format: ["esm", "cjs"],
        platform: "node",
        dts: true,
        sourcemap: true,
      },
      {
        entry: ["./src/core.ts"],
        platform: "browser",
        dts: true,
        minify: true,
        sourcemap: true,
      },
    ]);
  6. Eta ecosystem and integrations

    main

    Eta has several community-driven integrations for various tools and frameworks:

    • Visual Studio Code: eta-vscode for template editing.
    • ESLint: eslint-plugin-eta for linting Eta templates.
    • Node-RED: node-red-contrib-eta for using templates in Node-RED flows.
    • Koa: @cedx/koa-eta for rendering templates in the Koa web framework.
    • Vite: @rinoshiyo/vite-plugin-eta for using Eta in Vite projects.
  7. Handle Eta error types

    main

    When working with eta, you can catch specific error classes to distinguish between different failure modes during template processing. All specific errors inherit from EtaError.

    • EtaError: The base error class for all eta-related issues.
    • EtaParseError: Thrown when there is a syntax error during the parsing phase.
    • EtaRuntimeError: Thrown when an error occurs during template execution (e.g., accessing an undefined variable).
    • EtaFileResolutionError: Thrown when a template file cannot be located.
    • EtaNameResolutionError: Thrown when there is an issue resolving names within the template.
  8. Render templates asynchronously with renderAsync()

    main

    Use renderAsync() to render a template asynchronously. This returns a Promise<string>. It behaves similarly to render(), but sets the async option to true internally, which affects how templates are cached and how the template function is executed.

    Arguments:

    • template: A string representing the template name/path or a TemplateFunction.
    • data: An object containing the data to be used in the template.
    • meta: An optional object containing filepath to assist in template resolution.
  9. Use the Eta class for template rendering

    main
    The Eta class is the primary entrypoint for the library. It extends the internal core implementation and provides the interface for configuring and executing templates. You can import it directly to manage template compilation and rendering processes.
  10. Render raw template strings with renderString() and renderStringAsync()

    main

    If you have a raw template string that is not stored in a file, use renderString() or renderStringAsync(). These methods compile the string into a function before rendering.

    • renderString(template, data): Compiles the string and renders it synchronously.
    • renderStringAsync(template, data): Compiles the string and renders it asynchronously (returns a Promise).
  11. Compile a template string to a function string with `compileToString`

    main

    The compileToString method (available on an Eta instance) converts a template string into a string of executable JavaScript code. This generated string can then be used to create a new function via the new Function() constructor.

    This is a low-level method typically used internally by compile(). It respects the current Eta instance configuration and allows for overriding specific options like async for the resulting function.

    /**
     * Compiles a template string to a function string. Most often users just use `compile()`, which calls `compileToString` and creates a new function using the result
     */
    export function compileToString(
      this: Eta,
      str: string,
      options?: Partial<Options>,
    ): string