Powerful content text macros.
npm install "content-macros"
git clone "https://github.com/grumpygary/content-macros"
While javascript template strings are wonderful in most cases,
they're not well suited for content string macros.
content-macros
provides a way to implement and control
content string macros with: string-replacement, nested macros
(use macros to build macros), function sets, etc.
import ContentMacros from "content-macros";
const macros = new ContentMacros()
macros.expand(stringToExpend,options);
// or
macros.expand(options); // { text, values, functions, ... }
Macros begin with {{ and end with }} (customizable). They may be nested to create interesting results. Macros objects may have a state, which can be overridden when expanded.
There are 2 types of macros, depending on parameters passed to .expand():
-
stateless: (default) if not state is active (during instantiation or overridden), options.functions are called without a state. If the first character is "=" or "." it is ignored.
-
stateful: If state is active, the first argument to each function is the state: -- if the first character is "=", a value result is returned (defaults to options.empty) -- if the first character is ".", "" is returned
{{key,...args}} // assumes no active state
{{=key,...args}} // returns a value (whether stateless or stateful)
{{.key,...args}} // no value if stateful, returns result otherwise
See tests/jest-tests.js in repo for examples.
name | type | default | description
--------------|----------|-----------------|-------------------------------------------------
bom | string | "{{" | string marking beginning of macro
eom | string | "}}" | string marking end of macro
separator | string | "," | string used to split macro into arguments
functions | object | | dictionary of functions. state or stateful
state | boolean | | if exists, is passed as first parameter to functions
nesting | number | 5 | max recursion depth
empty | string | "" | what to return if expansion is empty
error | bool | false | log error if value not found
warn | bool | false | log warning if value not found
log | bool | false | console.log items
debug | bool | false | console.debug items
-
Functions in calls to expand() are ADDED to the functions used to intantiate the macro object. This allows for contextual functions.
-
"state" changes how macro function work. If using state, the state is passed as the first argument, followed by the arguments in the macro.
-
Be careful when using 'state'. Make sure you use either "{{.funcName}}" (return nothing) or "{{=funcName}}" (return value). They are optional otherwise.
import ContentMacros from "ContentMacros";
// const ContentMacros = require("content-macros");
let options = {
values: {
greeting: "Hello",
},
functions: {
say(...args) {
return `${args.join(" ")}!`
}
}
};
let contentMacros = new ContentMacros(options);
console.log(contentMacros.expand("{{say,{{greeting}},world}}"));
// "Hello world!"