Squirrelly Template Engine

website·Indexed 29 days ago

https://squirrelly.js.org/docs/

A template engine featuring language versatility and a small package size. The documentation covers syntax, filters, configuration options, performance benchmarks, and technical implementation details.

Tokens
3.3K
Snippets
20
Records
26
Agent score
67%

What's inside Squirrelly

  1. Squirrelly API Reference Overview

    The Squirrelly API provides a set of methods for template manipulation and configuration. Key options include compile, render, renderFile, parse, loadFile, filters, helpers, and nativeHelpers.
  2. Squirrelly feature overview and constraints

    Squirrelly is a lightweight (~4KB gzipped) template engine with 0 dependencies. Key characteristics include:

    • Language Agnostic: Works with HTML, Markdown, and other text-based languages.
    • Whitespace: Not whitespace sensitive by default (though trimming is configurable).
    • Features: Supports user-defined and native helpers, filters, partials, and custom delimiters.
    • Performance: Uses Regular Expressions to parse templates into a syntax tree, which is then compiled into a fast string-interpolation function.
  3. Implement logic with Helpers

    Helpers are used for logic, including conditionals, looping, and partials. They start with the @ symbol. Helpers can have blocks (starting with #) for logical separation or be self-closing if they only require parameters.
    {{! Block Helper }}
    {{@portfolio({userID: 3838357})}}
      Joe Edrick
      {{#tagline}}Cool Coder Person{{/tagline}}
    {{/portfolio}}
    
    {{! Self-Closing Helper }}
    {{@include("mypartial") /}}
    
    {{! Conditional Helper }}
    {{ @if (it.number === 3) }}
      Number is three
    {{ #elif (it.number === 4) }}
      Number is four
    {{ #else }}
      Number is five
    {{ /if}}
  4. Manage templates, filters, and helpers using Storage Containers

    Squirrelly uses Cacher objects to store templates, filters, and helpers. You can interact with these containers using the following methods:

    • .get('name'): Retrieve a cached item.
    • .define('name', value): Define or overwrite a cached item.
    • .load(cacheObj): Load an entire cache object.
    • .clear(): Reset the cache.
    // Define a partial template
    Sqrl.templates.define("my-partial", Sqrl.compile("This is a partial speaking"));
    
    // Retrieve a template
    console.log(Sqrl.templates.get("my-partial"));
    
    // Define a custom filter
    Sqrl.filters.define("capitalize", function(str) {
      return str.toUpperCase();
    });
    
    // Clear filters
    Sqrl.filters.clear();
  5. Execute JavaScript using Native Code (Evaluation) tags

    Native code tags insert valid JavaScript directly into the template function. These tags start with an exclamation mark !. They are commonly used for comments or simple function calls like console.log. Semicolons are required after function calls.
    {{! /* this is a comment */}}
    {{! console.log("Hi"); }}
  6. Post-process values using Filters

    Filters allow you to pipe content through predefined functions using the | symbol. Multiple filters can be chained together, and filters can accept parameters. Note that filters must be defined via the Filter API before they can be used. The safe filter is a special flag used to disable autoescaping.
    {{ mystring | reverse | capitalize }}
    {{ it.someArray | join(", ") }}
    {{ myreference | safe }}
  7. Implement Async Helpers and Rendering

    Squirrelly supports asynchronous helpers. To use them, prefix the helper or filter name with async in the template. When rendering, you must set async: true and list the async helpers in the asyncHelpers array within the options object. This can be handled via await or a callback.
    function resolveAfter2Seconds () {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('HI FROM ASYNC')
        }, 2000)
      })
    }
    
    Sqrl.helpers.define('async-test', resolveAfter2Seconds)
    
    // Using async/await
    async function doAsyncStuff () {
      console.log(
        await Sqrl.render(
          '{{@async async-test()/}}',
          {},
          { async: true, asyncHelpers: ['async-test'] }
        )
      )
    }
    
    // Using callbacks
    Sqrl.render(
      '{{@async async-test()/}}',
      {},
      { async: true, asyncHelpers: ['async-test'] },
      function (err, res) {
        console.log(res)
      }
    )
  8. Use Registered and File Partials

    Partials are implemented as self-closing helpers.

    1. Registered Partials: Work in both Browser and Node.js. They must be defined using Sqrl.templates.define() before use.
    2. File Partials: Work only in Node.js and do not require prior definition; they are loaded from the file system.
    // Registered Partial
    let mypartial = `My name is {{it.name}}`;
    Sqrl.templates.define('mypartial', Sqrl.compile(mypartial));
    Sqrl.render("This is a partial: {{@include('mypartial', it) /}}", { name: 'Ben' });
    
    // File Partial (Node.js only)
    // In template: {{@includeFile('./partial', it) /}}
    Sqrl.render("{{@includeFile('./partial', it) /}}", { name: 'Ben' });
  9. Create custom filters in Squirrelly

    Filters allow you to pass template values through a JavaScript function using the | pipe syntax. Filters can also accept parameters.
    // Simple filter: reverse a string
    Sqrl.filters.define("reverse", function(str) {
      return str.split("").reverse().join("");
    });
    // Template: "Hi, my name is {{it.name | reverse}}"
    
    // Filter with parameters: replace text
    Sqrl.filters.define("replace", function(str, search, replace) {
      return str.replace(search, replace);
    });
    // Template: "{{it.bio | replace('apples', 'watermelons') }}"
    
    Sqrl.render("Hi, my name is {{it.name | reverse}}", { name: "Ben" }); // Hi, my name is neB
  10. Install Squirrelly

    Squirrelly is provided as a UMD module, supporting ES modules, CommonJS, and AMD. It can be installed via npm or Yarn for Node.js environments, or included via CDN for browser use.
    # Using npm
    npm install squirrelly --save
    
    # Using Yarn
    yarn add squirrelly
    // ES Modules
    import * as Sqrl from 'squirrelly'
    
    // CommonJS
    var Sqrl = require('squirrelly')
    <!-- Unpkg -->
    <script src="https://unpkg.com/squirrelly"></script>
    
    <!-- JSDelivr -->
    <script src="https://cdn.jsdelivr.net/npm/squirrelly"></script>
  11. Interpolate data using References

    References (interpolations) output data into the template. By default, the data passed to a template is stored in an object named it. You can use dot notation or bracket notation to access properties. To disable autoescaping for a specific reference, prefix the reference with an asterisk * immediately after the opening delimiter.
    {{ it.user.lastName }}
    {{ it.user['lastName'] }}
    {{* unescapedSomething }}
  12. Integrate Squirrelly with Express.js

    Squirrelly provides a renderFile method that integrates directly with Express.js as a view engine.
    const app = require('express')();
    
    // Use .html extension
    app.engine('html', require('squirrelly').renderFile);
    
    // OR use .squirrelly extension
    app.set('view engine', 'squirrelly');