Skip to content

Commit

Permalink
new Template class
Browse files Browse the repository at this point in the history
  • Loading branch information
fballiano committed Dec 12, 2024
1 parent f5f5921 commit acecb26
Showing 1 changed file with 17 additions and 19 deletions.
36 changes: 17 additions & 19 deletions public/js/varien/js.js
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,7 @@ Calendar.initialize = async function(event) {

class Template
{
static #DEFAULT_PATTERN = /(?:^|.|\r|\n)(#\{(.*?)\})/g;
static #DEFAULT_PATTERN = /#\{(.*?)\}/g;

/**
* Creates a Template object for string interpolation
Expand All @@ -687,26 +687,24 @@ class Template
throw new TypeError('Data object cannot be null or undefined');
}

return this.template.replaceAll(this.pattern, (match, prefix = '', expr) => {
return this.template.replace(this.pattern, (match, expr) => {
try {
// Handle escape sequences
if (prefix === '\\') return match;

// Parse nested properties using optional chaining
const value = expr.split('.')
.reduce((obj, prop) => {
// Handle array notation [index]
const arrayMatch = prop.match(/(\w+)\[(\d+)\]/);
if (arrayMatch) {
const [, propName, index] = arrayMatch;
return obj?.[propName]?.[index];
}
return obj?.[prop];
}, data);

return `${prefix}${value ?? ''}`;
let value = data;
const parts = expr.trim().split('.');

for (const part of parts) {
if (part.includes('[')) {
const [name, index] = part.split('[');
const cleanIndex = parseInt(index.replace(']', ''));
value = value[name][cleanIndex];
} else {
value = value[part];
}
}

return value ?? '';
} catch (error) {
return `${prefix}`;
return '';
}
});
}
Expand Down

0 comments on commit acecb26

Please sign in to comment.