js-in-strings
Version:
A library for rendering templates with JavaScript expressions
70 lines (68 loc) • 2.34 kB
TypeScript
/**
* js-in-strings
* A library for rendering templates with JavaScript expressions
*/
/**
* Configuration options for renderTemplateWithJS
*/
interface RenderOptions {
/**
* If true, returns the raw evaluated value instead of converting to a string
*/
returnRawValues?: boolean;
/**
* If true, restricts access to global objects for security
*/
sandbox?: boolean;
/**
* Custom global objects to be provided when in sandbox mode
*/
allowedGlobals?: Record<string, any>;
/**
* Timeout in milliseconds for expression evaluation
* Default: 1000ms (1 second)
*/
timeout?: number;
/**
* Custom delimiters for expressions
* Default: ['{', '}']
*/
delimiters?: [string, string];
/**
* Additional context properties to extend the main context
*/
contextExtensions?: Record<string, any>;
/**
* If true, uses a more direct but less secure evaluation method
* Only use this if you trust the template source
* Default: false
*/
unsafeEval?: boolean;
}
/**
* Renders a template string with JavaScript expressions
*
* @param template - The template string containing JavaScript expressions wrapped in {}
* @param context - The context object containing values to be used in the template
* @param options - Optional configuration options
* @returns The rendered template with all expressions evaluated, or the raw evaluated expression if returnRawValues is true
*
* @example
* ```ts
* // String template rendering
* const template = "Hello, {name}! Your score is {Math.round(score)}.";
* const context = { name: "John", score: 95.6 };
* const result = renderTemplateWithJS(template, context);
* // "Hello, John! Your score is 96."
*
* // Raw value extraction
* const data = renderTemplateWithJS("{items.filter(i => i > 2)}", { items: [1, 2, 3, 4, 5] }, { returnRawValues: true });
* // Returns the actual array: [3, 4, 5]
*
* // Custom delimiters
* const customResult = renderTemplateWithJS("Hello, ${name}!", { name: "World" }, { delimiters: ["${" ,"}"] });
* // "Hello, World!"
* ```
*/
declare function renderTemplateWithJS<T = string>(template: string, context: Record<string, any>, options?: RenderOptions): T | string;
export { type RenderOptions, renderTemplateWithJS };