Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1b5e16ae5f | |||
| 1b0061b714 | |||
| 3048b74b2f | |||
| 49959f3060 | |||
| cabfc93773 | |||
| 38207eb618 | |||
| 1352e69895 | |||
| 1b05af09fb | |||
| 32c61fff42 |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.27.17",
|
||||
"version": "0.28.5",
|
||||
"description": "Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -122,6 +122,8 @@ export function sortByProp(prop: string, reverse = false) {
|
||||
return function (a: any, b: any) {
|
||||
const aVal = dotNotation<any>(a, prop);
|
||||
const bVal = dotNotation<any>(b, prop);
|
||||
if(aVal === undefined) return 1;
|
||||
if(bVal === undefined) return -1;
|
||||
if(typeof aVal == 'number' && typeof bVal == 'number')
|
||||
return (reverse ? -1 : 1) * (aVal - bVal);
|
||||
if(aVal > bVal) return reverse ? -1 : 1;
|
||||
|
||||
@@ -65,6 +65,8 @@ export class PathEvent {
|
||||
module!: string;
|
||||
/** Entire path, including the module & name */
|
||||
fullPath!: string;
|
||||
/** Parent directory, excludes module & name */
|
||||
dir!: string;
|
||||
/** Path including the name, excluding the module */
|
||||
path!: string;
|
||||
/** Last segment of path */
|
||||
@@ -121,6 +123,7 @@ export class PathEvent {
|
||||
if(p === '' || p === undefined || p === '*') {
|
||||
this.module = '';
|
||||
this.path = '';
|
||||
this.dir = '';
|
||||
this.fullPath = '**';
|
||||
this.name = '';
|
||||
this.methods = new ASet<Method>(p === '*' ? ['*'] : <any>method.split(''));
|
||||
@@ -132,6 +135,7 @@ export class PathEvent {
|
||||
let temp = p.split('/').filter(p => !!p);
|
||||
this.module = temp.splice(0, 1)[0] || '';
|
||||
this.path = temp.join('/');
|
||||
this.dir = temp.length > 2 ? temp.slice(0, -1).join('/') : '';
|
||||
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
|
||||
this.name = temp.pop() || '';
|
||||
this.hasGlob = this.fullPath.includes('*');
|
||||
|
||||
258
src/template.ts
258
src/template.ts
@@ -5,9 +5,76 @@ import {formatDate} from './time.ts';
|
||||
|
||||
export class TemplateError extends BadRequestError { }
|
||||
|
||||
export function findTemplateVars(html: string): Record<string, any> {
|
||||
const variables = new Set<string>();
|
||||
const arrays = new Set<string>();
|
||||
const excluded = new Set<string>(['true', 'false', 'null', 'undefined']);
|
||||
|
||||
// Extract & exclude loop variables, mark arrays
|
||||
for (const loop of matchAll(html, /\{\{\s*?\*\s*?(.+?)\s+in\s+(.+?)\s*?}}/g)) {
|
||||
const [element, index = 'index'] = loop[1].replaceAll(/[()\s]/g, '').split(',');
|
||||
excluded.add(element);
|
||||
excluded.add(index);
|
||||
const arrayVar = loop[2].trim();
|
||||
const root = arrayVar.split('.')[0];
|
||||
if(!excluded.has(root)) {
|
||||
variables.add(arrayVar);
|
||||
arrays.add(arrayVar);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract variables from if/else-if conditions
|
||||
for (const ifStmt of matchAll(html, /\{\{\s*?[!]?\?\s*?([^}]+?)\s*?}}/g)) {
|
||||
const code = ifStmt[1].replace(/["'`][^"'`]*["'`]/g, '');
|
||||
const cleaned = code.replace(/([a-zA-Z_$][a-zA-Z0-9_$.]*)\s*\(/g, (_, v) => {
|
||||
const parts = v.split('.');
|
||||
return parts.length > 1 ? parts.slice(0, -1).join('.') + ' ' : '';
|
||||
});
|
||||
const vars = cleaned.match(/[a-zA-Z_$][a-zA-Z0-9_$.]+/g) || [];
|
||||
for (const v of vars) {
|
||||
const root = v.split('.')[0];
|
||||
if(!excluded.has(root)) variables.add(v);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract from if block content & regular interpolations
|
||||
const regex = /\{\{\s*([^<>\*\?!/}\s][^}]*?)\s*}}/g;
|
||||
let match;
|
||||
while ((match = regex.exec(html)) !== null) {
|
||||
const code = match[1].trim().replace(/["'`][^"'`]*["'`]/g, '');
|
||||
const cleaned = code.replace(/([a-zA-Z_$][a-zA-Z0-9_$.]*)\s*\(/g, (_, v) => {
|
||||
const parts = v.split('.');
|
||||
return parts.length > 1 ? parts.slice(0, -1).join('.') + ' ' : '';
|
||||
});
|
||||
const vars = cleaned.match(/[a-zA-Z_$][a-zA-Z0-9_$.]+/g) || [];
|
||||
for (const v of vars) {
|
||||
const root = v.split('.')[0];
|
||||
if(!excluded.has(root)) variables.add(v);
|
||||
}
|
||||
}
|
||||
|
||||
const result: Record<string, any> = {};
|
||||
for (const path of variables) {
|
||||
const parts = path.split('.');
|
||||
let current = result;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
if(i === parts.length - 1) {
|
||||
const fullPath = parts.slice(0, i + 1).join('.');
|
||||
current[part] = arrays.has(fullPath) ? [] : '';
|
||||
} else {
|
||||
current[part] = current[part] || {};
|
||||
current = current[part];
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export async function renderTemplate(template: string, data: any, fetch?: (file: string) => Promise<string>) {
|
||||
let content = template, found: any;
|
||||
const now = new Date(), d = {
|
||||
if(!fetch) fetch = (file) => { throw new TemplateError(`Unable to fetch template: ${file}`); }
|
||||
|
||||
const now = new Date();
|
||||
const d = {
|
||||
date: {
|
||||
day: now.getDate(),
|
||||
month: now.toLocaleString('default', { month: 'long' }),
|
||||
@@ -18,64 +85,157 @@ export async function renderTemplate(template: string, data: any, fetch?: (file:
|
||||
...(data || {}),
|
||||
};
|
||||
|
||||
if(!fetch) fetch = (file) => {
|
||||
throw new TemplateError(`Unable to fetch template: ${file}`);
|
||||
}
|
||||
|
||||
const evaluate = (code: string, data: object, fatal = true) => {
|
||||
try {
|
||||
return Function('data', `Object.assign(this, data); return ${code};`)(data);
|
||||
} catch {
|
||||
if(fatal) throw new TemplateError(`Failed to evaluate: ${code}`);
|
||||
else return false;
|
||||
return Function('data', `with(data) { return ${code}; }`)(data);
|
||||
} catch(err: any) {
|
||||
if(fatal) throw new TemplateError(`Failed to evaluate: ${code}\n${err.message || err.toString()}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// If Statements - Optimize what we render: `{{ ? javascript }} TRUE CONTENT {{ !? }} FALSE CONTENT {{ /? }}`
|
||||
while(!!(found = /\{\{\s*?\?\s*?(.+?)\s*?}}([\s\S]*?)(?:\{\{\s*?!\?\s*?}}([\s\S]*?))?\{\{\s*?\/\?\s*?}}/g.exec(content))) {
|
||||
const nested = matchAll(found[0], /\{\{\s*?\?.+?}}/g).slice(-1)?.[0]?.index;
|
||||
if(nested != 0)
|
||||
found = /\{\{\s*?\?\s*?(.+?)\s*?}}([\s\S]*?)(?:\{\{\s*?!\?\s*?}}([\s\S]*?))?\{\{\s*?\/\?\s*?}}/g.exec(content.slice(found.index + nested))
|
||||
content = content.replace(found[0], (evaluate(found[1], d, false) ? found[2] : found[3]) || '');
|
||||
}
|
||||
async function process(content: string, ctx: object = d): Promise<string> {
|
||||
let result = content;
|
||||
|
||||
// Imports - We render bottom up: `{{ < file.html }}`
|
||||
while(!!(found = /\{\{\s*?<\s*?(.+?)\s*?}}/g.exec(content))) {
|
||||
content = content.replace(found[0], await renderTemplate(await fetch(found[1].trim()), data, fetch));
|
||||
}
|
||||
|
||||
// For Loops: `{{ * (row, index) in invoice }} CONTENT {{ /* }}`
|
||||
while(!!(found = /\{\{\s*?\*\s*?(.+?)\s+in\s+(.+?)\s*?}}([\s\S]*?)\{\{\s*?\/\*\s*?}}/g.exec(content))) {
|
||||
const split = found[1].replaceAll(/[()\s]/g, '').split(',');
|
||||
const element = split[0];
|
||||
const index = split[1] || 'index';
|
||||
const array: any[] = <any>dotNotation(data, found[2]);
|
||||
if(!array || typeof array != 'object')
|
||||
throw new TemplateError(`Cannot iterate: ${found[2]}`);
|
||||
|
||||
let compiled = [];
|
||||
for(let i = 0; i < array.length; i++) {
|
||||
compiled.push(renderTemplate(found[3], {
|
||||
...d,
|
||||
[element]: array[i],
|
||||
[index]: i
|
||||
}, fetch))
|
||||
// Process extends first (they wrap everything)
|
||||
const extendsMatch = result.match(/\{\{\s*>\s*(.+?):(.+?)\s*}}([\s\S]*?)\{\{\s*\/>\s*}}/);
|
||||
if(extendsMatch) {
|
||||
const parentTemplate = await (<Function>fetch)(extendsMatch[1].trim());
|
||||
if(!parentTemplate) throw new TemplateError(`Unknown extended template: ${extendsMatch[1].trim()}`);
|
||||
const slotName = extendsMatch[2].trim();
|
||||
const slotContent = await process(extendsMatch[3], ctx);
|
||||
return process(parentTemplate, {...ctx, [slotName]: slotContent});
|
||||
}
|
||||
content = content.replace(found[0], compiled.join('\n'));
|
||||
|
||||
let changed = true;
|
||||
while(changed) {
|
||||
changed = false;
|
||||
const before = result;
|
||||
|
||||
// Process imports
|
||||
const importMatch = result.match(/\{\{\s*<\s*(.+?)\s*}}/);
|
||||
if(importMatch) {
|
||||
const t = await (<Function>fetch)(importMatch[1].trim());
|
||||
if(!t) throw new TemplateError(`Unknown imported template: ${importMatch[1].trim()}`);
|
||||
const rendered = await process(t, ctx);
|
||||
result = result.replace(importMatch[0], rendered);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Process for-loops (innermost first)
|
||||
const forMatch = findInnermostFor(result);
|
||||
if(forMatch) {
|
||||
const { full, vars, array, body, start } = forMatch;
|
||||
const [element, index = 'index'] = vars.split(',').map(v => v.trim());
|
||||
const arr: any[] = <any>dotNotation(ctx, array);
|
||||
if(!arr || typeof arr != 'object') throw new TemplateError(`Cannot iterate: ${array}`);
|
||||
let output = [];
|
||||
for(let i = 0; i < arr.length; i++)
|
||||
output.push(await process(body, {...ctx, [element]: arr[i], [index]: i}));
|
||||
result = result.slice(0, start) + output.join('\n') + result.slice(start + full.length);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Process if-statements (innermost first)
|
||||
const ifMatch = findInnermostIf(result);
|
||||
if(ifMatch) {
|
||||
const { full, condition, body, start } = ifMatch;
|
||||
const branches = parseIfBranches(body);
|
||||
let output = '';
|
||||
if(evaluate(condition, ctx, false)) {
|
||||
output = branches.if;
|
||||
} else {
|
||||
for(const branch of branches.elseIf) {
|
||||
if(evaluate(branch.condition, ctx, false)) {
|
||||
output = branch.body;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!output && branches.else) output = branches.else;
|
||||
}
|
||||
result = result.slice(0, start) + output + result.slice(start + full.length);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if(before === result) changed = false;
|
||||
}
|
||||
return processVariables(result, ctx);
|
||||
}
|
||||
|
||||
// Evaluate whatever is left - Should come last: `{{ javascript }}`
|
||||
while(!!(found = /\{\{\s*([^<>\*\?!/}\s][^}]*?)\s*}}/g.exec(content))) {
|
||||
content = content.replace(found[0], evaluate(found[1].trim(), d) || '');
|
||||
function processVariables(content: string, data: object): string {
|
||||
return content.replace(/\{\{\s*([^<>\*\?!/}\s][^{}]*?)\s*}}/g, (match, code) => {
|
||||
return evaluate(code.trim(), data) ?? '';
|
||||
});
|
||||
}
|
||||
|
||||
// Extends: `{{ > file.html:property }} CONTENT {{ /> }}`
|
||||
while(!!(found = /\{\{\s*?>\s*?(.+?):(.+?)\s*?}}([\s\S]*?)\{\{\s*?\/>\s*?}}/g.exec(content))) {
|
||||
content = content.replace(found[0], await renderTemplate(await fetch(found[1].trim), {
|
||||
...data,
|
||||
[found[2].trim()]: found[3],
|
||||
}, fetch));
|
||||
function findInnermostIf(content: string) {
|
||||
const regex = /\{\{\s*\?\s*(.+?)\s*}}/g;
|
||||
let match, lastMatch = null;
|
||||
while((match = regex.exec(content)) !== null) {
|
||||
const start = match.index;
|
||||
const condition = match[1];
|
||||
const bodyStart = match.index + match[0].length;
|
||||
const end = findMatchingClose(content, bodyStart, /\{\{\s*\?\s*/, /\{\{\s*\/\?\s*}}/);
|
||||
if(end === -1) throw new TemplateError(`Unmatched if-statement at position ${start}`);
|
||||
const closeTag = content.slice(end).match(/\{\{\s*\/\?\s*}}/);
|
||||
const full = content.slice(start, end + (<any>closeTag)[0].length);
|
||||
const body = content.slice(bodyStart, end);
|
||||
lastMatch = { full, condition, body, start };
|
||||
}
|
||||
return lastMatch;
|
||||
}
|
||||
|
||||
return content;
|
||||
function findInnermostFor(content: string) {
|
||||
const regex = /\{\{\s*\*\s*(.+?)\s+in\s+(.+?)\s*}}/g;
|
||||
let match, lastMatch = null;
|
||||
while((match = regex.exec(content)) !== null) {
|
||||
const start = match.index;
|
||||
const vars = match[1].replaceAll(/[()\s]/g, '');
|
||||
const array = match[2];
|
||||
const bodyStart = match.index + match[0].length;
|
||||
const end = findMatchingClose(content, bodyStart, /\{\{\s*\*\s*/, /\{\{\s*\/\*\s*}}/);
|
||||
if(end === -1) throw new TemplateError(`Unmatched for-loop at position ${start}`);
|
||||
const closeTag = content.slice(end).match(/\{\{\s*\/\*\s*}}/);
|
||||
const full = content.slice(start, end + (<any>closeTag)[0].length);
|
||||
const body = content.slice(bodyStart, end);
|
||||
lastMatch = { full, vars, array, body, start };
|
||||
}
|
||||
return lastMatch;
|
||||
}
|
||||
|
||||
function findMatchingClose(content: string, startIndex: number, openTag: RegExp, closeTag: RegExp): number {
|
||||
let depth = 1, pos = startIndex;
|
||||
while (depth > 0 && pos < content.length) {
|
||||
const remaining = content.slice(pos);
|
||||
const nextOpen = remaining.search(openTag);
|
||||
const nextClose = remaining.search(closeTag);
|
||||
if(nextClose === -1) return -1;
|
||||
if(nextOpen !== -1 && nextOpen < nextClose) {
|
||||
depth++;
|
||||
pos += nextOpen + 1;
|
||||
} else {
|
||||
depth--;
|
||||
if(depth === 0) return pos + nextClose;
|
||||
pos += nextClose + 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function parseIfBranches(body: string) {
|
||||
const parts = body.split(/\{\{\s*!\?\s*/);
|
||||
const result = { if: parts[0], elseIf: [] as any[], else: '' };
|
||||
for(let i = 1; i < parts.length; i++) {
|
||||
const closeBrace = parts[i].indexOf('}}');
|
||||
const condition = parts[i].slice(0, closeBrace).trim();
|
||||
const branchBody = parts[i].slice(closeBrace + 2);
|
||||
if(!condition) result.else = branchBody;
|
||||
else result.elseIf.push({ condition, body: branchBody });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
return process(template);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,11 @@ describe('Object utilities', () => {
|
||||
dotNotation(obj, 'd.e.f', 5);
|
||||
expect(obj.d.e.f).toBe(5);
|
||||
});
|
||||
it('undefined', () => {
|
||||
const obj: any = {a: 1};
|
||||
const resp = dotNotation(obj, 'a.b');
|
||||
expect(resp).toBe(undefined);
|
||||
})
|
||||
});
|
||||
|
||||
describe('encodeQuery', () => {
|
||||
|
||||
304
tests/templates.spec.ts
Normal file
304
tests/templates.spec.ts
Normal file
@@ -0,0 +1,304 @@
|
||||
import {findTemplateVars, renderTemplate, TemplateError} from '../src';
|
||||
|
||||
describe('findTemplateVars', () => {
|
||||
test('extracts simple variables', () => {
|
||||
const result = findTemplateVars('Hello {{ name }}!');
|
||||
expect(result).toEqual({ name: '' });
|
||||
});
|
||||
|
||||
test('extracts nested object paths', () => {
|
||||
const result = findTemplateVars('{{ user.name }} is {{ user.age }}');
|
||||
expect(result).toEqual({ user: { name: '', age: '' } });
|
||||
});
|
||||
|
||||
test('extracts variables from if statements', () => {
|
||||
const result = findTemplateVars('{{ ? active }}{{ message }}{{ /? }}');
|
||||
expect(result).toEqual({ active: '', message: '' });
|
||||
});
|
||||
|
||||
test('extracts variables from else-if conditions', () => {
|
||||
const result = findTemplateVars('{{ ? status == "paid" }}PAID{{ !? status == "pending" }}{{ value }}{{ /? }}');
|
||||
expect(result).toEqual({ status: '', value: '' });
|
||||
});
|
||||
|
||||
test('extracts array reference from loops', () => {
|
||||
const result = findTemplateVars('{{ * item in items }}{{ item }}{{ /* }}');
|
||||
expect(result).toEqual({ items: [] });
|
||||
});
|
||||
|
||||
test('excludes loop element variable', () => {
|
||||
const result = findTemplateVars('{{ * item in items }}{{ item.name }}{{ /* }}');
|
||||
expect(result).toEqual({ items: [] });
|
||||
expect(result).not.toHaveProperty('item');
|
||||
});
|
||||
|
||||
test('excludes loop index variable', () => {
|
||||
const result = findTemplateVars('{{ * (item, i) in items }}{{ i }}:{{ item }}{{ /* }}');
|
||||
expect(result).toEqual({ items: [] });
|
||||
expect(result).not.toHaveProperty('item');
|
||||
expect(result).not.toHaveProperty('i');
|
||||
});
|
||||
|
||||
test('extracts external vars used inside loops', () => {
|
||||
const result = findTemplateVars('{{ * item in items }}{{ item }}-{{ prefix }}{{ /* }}');
|
||||
expect(result).toEqual({ items: [], prefix: '' });
|
||||
});
|
||||
|
||||
test('handles nested loops', () => {
|
||||
const result = findTemplateVars('{{ * row in rows }}{{ * col in row.cols }}{{ col }}{{ /* }}{{ /* }}');
|
||||
expect(result).toEqual({ rows: [] });
|
||||
expect(result).not.toHaveProperty('row');
|
||||
expect(result).not.toHaveProperty('col');
|
||||
});
|
||||
|
||||
test('extracts from complex nested template', () => {
|
||||
const tpl = `
|
||||
{{ ? items.length > 0 }}
|
||||
{{ * (item, i) in items }}
|
||||
{{ i }}. {{ item.name }}: {{ currency }}{{ item.price }}
|
||||
{{ /* }}
|
||||
Total: {{ total }}
|
||||
{{ !? }}
|
||||
{{ emptyMessage }}
|
||||
{{ /? }}`;
|
||||
const result = findTemplateVars(tpl);
|
||||
expect(result).toEqual({
|
||||
items: [],
|
||||
currency: '',
|
||||
total: '',
|
||||
emptyMessage: ''
|
||||
});
|
||||
expect(result).not.toHaveProperty('item');
|
||||
expect(result).not.toHaveProperty('i');
|
||||
});
|
||||
|
||||
test('ignores template control syntax', () => {
|
||||
const result = findTemplateVars('{{ < header.html }}{{ > layout.html:content }}content{{ /> }}');
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
test('handles multiple variables in expressions', () => {
|
||||
const result = findTemplateVars('{{ firstName + " " + lastName }}');
|
||||
expect(result).toEqual({ firstName: '', lastName: '' });
|
||||
});
|
||||
|
||||
test('creates arrays for loop variables', () => {
|
||||
const result = findTemplateVars('{{ * item in items }}{{ item }}{{ /* }}');
|
||||
expect(result).toEqual({ items: [] });
|
||||
});
|
||||
|
||||
test('creates nested arrays', () => {
|
||||
const result = findTemplateVars('{{ * row in data.rows }}{{ row }}{{ /* }}');
|
||||
expect(result).toEqual({ data: { rows: [] } });
|
||||
});
|
||||
|
||||
test('creates multiple arrays', () => {
|
||||
const result = findTemplateVars('{{ * user in users }}{{ user }}{{ /* }}{{ * post in posts }}{{ post }}{{ /* }}');
|
||||
expect(result).toEqual({ users: [], posts: [] });
|
||||
});
|
||||
|
||||
test('excludes function calls', () => {
|
||||
const result = findTemplateVars('{{ value.toFixed(2) }}');
|
||||
expect(result).toEqual({ value: '' });
|
||||
expect(result.value).not.toBe('toFixed');
|
||||
});
|
||||
|
||||
test('excludes method chains', () => {
|
||||
const result = findTemplateVars('{{ text.replaceAll("\\n", "<br>") }}');
|
||||
expect(result).toEqual({ text: '' });
|
||||
});
|
||||
|
||||
test('handles mix of arrays and regular variables', () => {
|
||||
const result = findTemplateVars('{{ * item in cart }}{{ item.name }}{{ /* }}{{ total }}');
|
||||
expect(result).toEqual({ cart: [], total: '' });
|
||||
});
|
||||
|
||||
test('real world template', async () => {
|
||||
const wrapper = `<div> {{body}} </div>`;
|
||||
const tpl = `
|
||||
{{ > email:body }}
|
||||
<div style="text-align: center">
|
||||
{{ ? title }}<h1 style="margin: 0">{{ title }}</h1>{{ /? }}
|
||||
{{ ? subject }}<h2 style="margin: 0">{{ subject }}</h2>{{ /? }}
|
||||
{{ ? message }}<p style="margin-top: 1rem">{{ message }}</p>{{ /? }}
|
||||
{{ ? link }}
|
||||
<br>
|
||||
<div style="background: #dedede; padding: 8px 20px; border-radius: 10px; overflow-x: auto;">
|
||||
{{ ? link.startsWith('http') }}
|
||||
<a style="word-break: break-all;" target="_blank" href="{{ link }}">{{ link }}</a>
|
||||
{{ !? }}
|
||||
<p style="margin: 0; word-break: break-all;">{{ link }}</p>
|
||||
{{ /? }}
|
||||
</div>
|
||||
{{ /? }}
|
||||
{{ ? footer }}
|
||||
<br>
|
||||
<p>{{ footer }}</p>
|
||||
{{ /? }}
|
||||
</div>
|
||||
{{ /> }}`;
|
||||
console.log(await renderTemplate(tpl, {
|
||||
title: 'test',
|
||||
subject: 'test',
|
||||
message: 'test',
|
||||
link: 'test',
|
||||
footer: 'test',
|
||||
}, async () => wrapper))
|
||||
});
|
||||
|
||||
test('real world invoice template', () => {
|
||||
const tpl = `
|
||||
{{ settings.title }}
|
||||
{{ * (row, index) in transaction.cart }}
|
||||
{{ row.quantity }} x {{ row.name }} = \${{ row.cost.toFixed(2) }}
|
||||
{{ /* }}
|
||||
Total: \${{ transaction.total.toFixed(2) }}
|
||||
{{ ? transaction.discount }}
|
||||
Discount: {{ transaction.discount.value }}
|
||||
{{ /? }}
|
||||
`;
|
||||
const result = findTemplateVars(tpl);
|
||||
expect(result).toEqual({
|
||||
settings: { title: '' },
|
||||
transaction: {
|
||||
cart: [],
|
||||
total: '',
|
||||
discount: { value: '' }
|
||||
}
|
||||
});
|
||||
expect(result).not.toHaveProperty('row');
|
||||
expect(result).not.toHaveProperty('index');
|
||||
expect(result.transaction.cart).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderTemplate', () => {
|
||||
test('basic variable interpolation', async () => {
|
||||
const result = await renderTemplate('Hello {{ name }}!', { name: 'World' });
|
||||
expect(result).toBe('Hello World!');
|
||||
});
|
||||
|
||||
test('nested object access', async () => {
|
||||
const result = await renderTemplate('{{ user.name }} is {{ user.age }}', {
|
||||
user: { name: 'Alice', age: 25 }
|
||||
});
|
||||
expect(result).toBe('Alice is 25');
|
||||
});
|
||||
|
||||
test('method calls', async () => {
|
||||
const result = await renderTemplate('{{ price.toFixed(2) }}', { price: 9.5 });
|
||||
expect(result).toBe('9.50');
|
||||
});
|
||||
|
||||
test('if statement true', async () => {
|
||||
const result = await renderTemplate('{{ ? active }}YES{{ /? }}', { active: true });
|
||||
expect(result).toBe('YES');
|
||||
});
|
||||
|
||||
test('if statement false', async () => {
|
||||
const result = await renderTemplate('{{ ? active }}YES{{ /? }}', { active: false });
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
test('if-else', async () => {
|
||||
const result = await renderTemplate('{{ ? active }}YES{{ !? }}NO{{ /? }}', { active: false });
|
||||
expect(result).toBe('NO');
|
||||
});
|
||||
|
||||
test('if-elseif-else', async () => {
|
||||
const tpl = '{{ ? status == "paid" }}PAID{{ !? status == "pending" }}PENDING{{ !? }}OTHER{{ /? }}';
|
||||
expect(await renderTemplate(tpl, { status: 'paid' })).toBe('PAID');
|
||||
expect(await renderTemplate(tpl, { status: 'pending' })).toBe('PENDING');
|
||||
expect(await renderTemplate(tpl, { status: 'failed' })).toBe('OTHER');
|
||||
});
|
||||
|
||||
test('nested if statements', async () => {
|
||||
const tpl = '{{ ? a }}A{{ ? b }}B{{ /? }}{{ /? }}';
|
||||
expect(await renderTemplate(tpl, { a: true, b: true })).toBe('AB');
|
||||
expect(await renderTemplate(tpl, { a: true, b: false })).toBe('A');
|
||||
expect(await renderTemplate(tpl, { a: false, b: true })).toBe('');
|
||||
});
|
||||
|
||||
test('for loop', async () => {
|
||||
const tpl = '{{ * item in items }}{{ item }}{{ /* }}';
|
||||
const result = await renderTemplate(tpl, { items: ['a', 'b', 'c'] });
|
||||
expect(result).toBe('a\nb\nc');
|
||||
});
|
||||
|
||||
test('for loop with index', async () => {
|
||||
const tpl = '{{ * (item, i) in items }}{{ i }}:{{ item }}{{ /* }}';
|
||||
const result = await renderTemplate(tpl, { items: ['a', 'b'] });
|
||||
expect(result).toBe('0:a\n1:b');
|
||||
});
|
||||
|
||||
test('for loop with objects', async () => {
|
||||
const tpl = '{{ * user in users }}{{ user.name }}{{ /* }}';
|
||||
const result = await renderTemplate(tpl, {
|
||||
users: [{ name: 'Alice' }, { name: 'Bob' }]
|
||||
});
|
||||
expect(result).toBe('Alice\nBob');
|
||||
});
|
||||
|
||||
test('for loop error on non-array', async () => {
|
||||
await expect(
|
||||
renderTemplate('{{ * x in notArray }}{{ x }}{{ /* }}', { notArray: 'string' })
|
||||
).rejects.toThrow(TemplateError);
|
||||
});
|
||||
|
||||
test('import template', async () => {
|
||||
const fetch = async (file: string) => {
|
||||
if (file === 'header.html') return 'HEADER: {{ title }}';
|
||||
throw new Error('Not found');
|
||||
};
|
||||
const result = await renderTemplate('{{ < header.html }}', { title: 'Test' }, fetch);
|
||||
expect(result).toBe('HEADER: Test');
|
||||
});
|
||||
|
||||
test('import template error', async () => {
|
||||
await expect(
|
||||
renderTemplate('{{ < missing.html }}', {})
|
||||
).rejects.toThrow(TemplateError);
|
||||
});
|
||||
|
||||
test('extend template', async () => {
|
||||
const fetch = async (file: string) => {
|
||||
if (file === 'layout.html') return '<div>{{ content }}</div>';
|
||||
throw new Error('Not found');
|
||||
};
|
||||
const result = await renderTemplate('{{ > layout.html:content }}Hello{{ /> }}', {}, fetch);
|
||||
expect(result).toBe('<div>Hello</div>');
|
||||
});
|
||||
|
||||
test('date object', async () => {
|
||||
const result = await renderTemplate('{{ date.year }}', {});
|
||||
expect(result).toBe(new Date().getFullYear().toString());
|
||||
});
|
||||
|
||||
test('evaluation error', async () => {
|
||||
await expect(
|
||||
renderTemplate('{{ undefined.property }}', {})
|
||||
).rejects.toThrow(TemplateError);
|
||||
});
|
||||
|
||||
test('complex nested example', async () => {
|
||||
const tpl = `
|
||||
{{ ? items.length > 0 }}
|
||||
{{ * (item, i) in items }}
|
||||
{{ i + 1 }}. {{ item.name }}: \${{ item.price.toFixed(2) }}
|
||||
{{ /* }}
|
||||
Total: \${{ total.toFixed(2) }}
|
||||
{{ !? }}
|
||||
No items
|
||||
{{ /? }}`;
|
||||
const result = await renderTemplate(tpl, {
|
||||
items: [
|
||||
{ name: 'A', price: 10 },
|
||||
{ name: 'B', price: 20 }
|
||||
],
|
||||
total: 30
|
||||
});
|
||||
expect(result.trim()).toContain('1. A: $10.00');
|
||||
expect(result.trim()).toContain('2. B: $20.00');
|
||||
expect(result.trim()).toContain('Total: $30.00');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user