trying to complete my task - create HTML builder. It works almost fine, but when I try test chaining case - throws Error. I understand that I need to return object to make chaining work, and we can create our custom toString(). But in this case I don't know where to save html strings data.
class Templater {
transform(tags) {
return tags.join("");
}
//function returns array where [0] = atttibutes, [1] = innerText or innerNodes
attributesCheck(tags) {
let attributeObject = {};
tags.forEach((item) => {
if(typeof item === 'object' && item !== null && !Array.isArray(item)) {
attributeObject = item;
}
})
const content = tags.filter(item => typeof item !== 'object')
let objectArr = Object.entries(attributeObject);
let classIndex;
let idIndex;
objectArr.forEach((item, index) => {
if(item[0] === 'class') {
classIndex = index;
}
if (item[0] === 'id') {
idIndex = index;
}
})
const classItem = objectArr[classIndex];
const idItem = objectArr[idIndex];
objectArr = objectArr.filter(item => item[0] !== 'class' && item[0] !== 'id')
if (idItem) {
objectArr.unshift(idItem);
}
if (classItem) {
objectArr.unshift(classItem);
}
let attrString = '';
objectArr.forEach(item => {
attrString += ` ${item[0]}="${item[1]}"`
})
return [attrString, content];
}
div(...tags) {
return `<div${this.attributesCheck(tags)[0]}>${this.transform(this.attributesCheck(tags)[1])}</div>`;
}
span(...tags) {
return `<span${this.attributesCheck(tags)[0]}>${this.transform(this.attributesCheck(tags)[1])}</span>`;
}
br(argument) {
if (argument) {
throw new Error('Nested content is not allowed');
} else {
return `<br>`;
}
}
p(...tags) {
return `<p${this.attributesCheck(tags)[0]}>${this.transform(this.attributesCheck(tags)[1])}</p>`;
}
}
const template = new Templater();
console.log(template.div('1454', {id: 'fixing'}).toString());
console.log(template.div('World of Templates', {id: "card", class: 'first'}).toString());
//nesting works
console.log(template.div(
template.p('Hello', {id: 'fix', class: "first-p"}),
template.p('World')
).toString());
//chaining DOESN'T
template.span('Hello').span('World').toString()