Fork me on GitHub

Shift Template

generates a Shift AST from Shift templating markup


Demo

This demo shows a rendering of the Template output on the right. You may edit the template on the left, and the template parameters in the center. The template parameters here are passed directly to the second argument of applyStructuredTemplate.

{ foo: node => new Shift.IdentifierExpression({name: node.name + '_'}), bar: node => new Shift.LiteralNumericExpression({value: node.value + 1}), }
a + /*# foo # IdentifierExpression #*/ b; 0 + /*# bar #*/ 1;

Installation

npm install shift-template

Usage

import Shift from "shift-ast";
import { applyTemplate } from "shift-template";
let src = `
a + /*# foo # IdentifierExpression #*/ b;
0 + /*# bar #*/ 1;
`;
let replaced = applyTemplate(src, {
  foo: node => new Shift.IdentifierExpression({ name: node.name + '_' }),
  bar: node => new Shift.LiteralNumericExpression({ value: node.value + 1 }),
});
/* replaced is an AST representing:
a + b_;
0 + 2;
*/
import Shift from "shift-ast";
import { applyStructuredTemplate } from "shift-template";
let src = `
[
  /*# if markerAtStart #*/
    { prop: 'marker' },
  /*# for each x of xs #*/
    { prop: /*# x::prop #*/ null },
  /*# unless markerAtStart #*/
    { prop: 'marker' },
]
`;

let templateValues = {
  markerAtStart: false,
  xs: [
    { prop: () => new Shift.LiteralNumericExpression({ value: 1 }) },
    { prop: () => new Shift.LiteralNumericExpression({ value: 2 }) },
    { prop: () => new Shift.LiteralNumericExpression({ value: 3 }) },
  ]
};

let replaced = applyStructuredTemplate(script, templateValues);
/* replaced is an AST representing:
[
  { prop: 1 },
  { prop: 2 },
  { prop: 3 },
  { prop: 'marker' },
]
*/
import { parseScriptWithLocation } from "shift-parser";
import { findNodes } from "shift-template";
let { tree, location, comments } = parseScriptWithLocation("/* ECMAScript program template markup */");
let names = findNodes({ tree, locations, comments });
/* names =
[
  {
    name: "foo",
    node: {
      type: "IdentifierExpression",
      name: "b",
    },
    comment: { text, type, start, end },
  },
  {
    name: "bar",
    node: {
      type: "LiteralNumericExpression",
      value: 1,
    },
    comment: { text, type, start, end },
  },
]
*/