All files / lib/core/renderer renderTemplate.js

91.42% Statements 32/35
92.85% Branches 13/14
100% Functions 1/1
91.42% Lines 32/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3712x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 57x 54x 54x 54x 54x 54x 2x 2x 54x 9x 9x 43x 53x       57x 57x 12x    
import { AvenxErrorCodes, formatMessage } from '../runtime/AvenxError.js';
import { HtmlEscaper, SafeHtml } from '../security/escapeHtml.js';
 
const escaper = new HtmlEscaper();
 
/**
 * Handles the rendering of HTML templates by resolving interpolation expressions.
 */
export class TemplateRenderer {
    /**
     * Renders the template by replacing {{ expression }} and {{{ expression }}} with evaluated values.
     * @param {string} template - The HTML template string.
     * @param {function(string): any} resolveExpression - Function to evaluate expressions.
     * @returns {string} The rendered HTML string.
     */
    render(template, resolveExpression) {
        return template.replace(/\{\{\{\s*(.*?)\s*\}\}\}|\{\{\s*(.*?)\s*\}\}/g, (match, gp1, gp2) => {
            const isRaw = gp1 !== undefined;
            const expression = isRaw ? gp1 : gp2;
            try {
                const value = resolveExpression(expression);
                if (value == null) {
                    return '';
                }
                if (isRaw || value instanceof SafeHtml) {
                    return String(value);
                }
                return escaper.escape(value);
            } catch (error) {
                console.warn(formatMessage(AvenxErrorCodes.TEMPLATE_RENDER_ERROR, expression, error));
                return '';
            }
        });
    }
}