@domchristie/composite
Advanced tools
Comparing version 0.1.1 to 0.3.0
/** | ||
* Renders a template with given properties. | ||
* | ||
* @param {HTMLElement} template - The HTML element containing the template string. | ||
* @param {HTMLTemplateElement|string} template - The HTML template to be rendered. | ||
* @param {Object} props - An object containing properties to be interpolated into the template. | ||
@@ -9,4 +9,7 @@ * @returns {string} The rendered HTML string with properties interpolated. | ||
export function fill (template, props) { | ||
template = template instanceof HTMLElement | ||
? template.innerHTML | ||
: String(template) | ||
return (new Function('html', 'raw', ...Object.keys(props), | ||
`return html\`${template.innerHTML}\`` | ||
`return html\`${template}\`` | ||
))(html, raw, ...Object.values(props)) | ||
@@ -32,9 +35,31 @@ } | ||
function escape (string) { | ||
const div = document.createElement('div') | ||
div.appendChild(document.createTextNode(string)) | ||
return div.innerHTML | ||
const entities = { | ||
'&': '&', | ||
'<': '<', | ||
'>': '>', | ||
'"': '"', | ||
"'": ''', | ||
'/': '/', | ||
'`': '`', | ||
'=': '=' | ||
} | ||
function raw (html) { | ||
/** | ||
* Escapes special characters in a string for use in HTML. | ||
* The characters escaped are: & < > " ' ` = / | ||
* | ||
* @param {string} string - The input string to escape. | ||
* @returns {string} - The escaped string. | ||
*/ | ||
export function escape (string) { | ||
return String(string).replace(/[&<>"'`=\/]/g, (s) => entities[s]) | ||
} | ||
/** | ||
* Marks a string as raw HTML to prevent escaping of special characters. | ||
* | ||
* @param {string} html - The HTML string to wrap. | ||
* @returns {RawString} - The wrapped HTML string as a RawString object. | ||
*/ | ||
export function raw (html) { | ||
return new RawString(html) | ||
@@ -41,0 +66,0 @@ } |
{ | ||
"name": "@domchristie/composite", | ||
"version": "0.1.1", | ||
"version": "0.3.0", | ||
"description": "A hybrid client-side/server-side approach to generating dynamic HTML.", | ||
@@ -5,0 +5,0 @@ "main": "composite.js", |
@@ -5,3 +5,3 @@ # 🦷 Composite | ||
Compose your HTML in `<template>` elements. Use placeholders (`${…}`) to mark dynamic content. Call `fill` to generate a new HTML string which interpolates the template's content with given properties. | ||
Compose your HTML in `<template>` elements. Use placeholders (`${…}`) to mark dynamic content. Call `fill` to generate a new HTML string which interpolates the template's content with the given properties. | ||
@@ -8,0 +8,0 @@ ## Usage |
6583
101