Home > OS >  Implement a class to generate HTML
Implement a class to generate HTML

Time:12-05

This is what I want to do

HTMLConstruct.span('foo'); // -> <span>foo</span>
HTMLConstruct.div.span('bar'); // -> <div><span>bar</span></div>

HTMLConstruct.div.p(
  HTMLConstruct.span('bar'),
  HTMLConstruct.div.span('baz')
); // -> <div><p><span>bar</span><span>baz</span></p></div>

I made this but it`s not work as it should. I have no idea how to implement it

class TestClass {
  private str: string
  constructor(str?: string) {
    this.str = str || ''
  }
  
  div(str: string): TestClass {
    str = `<div>${str}</div>`
    return new TestClass(str)
  }
}

CodePudding user response:

Here's one way you could implement the HTMLConstruct class to make it work as described in your example:

class HTMLConstruct {
  elementStack: string[] = []
  str: string = ''

  constructor(str: string = '') {
    this.str = str
  }

  div(...strs: HTMLConstruct[]): HTMLConstruct {
    this.elementStack.unshift('div')
    return this.addStrings(strs)
  }

  span(...strs: HTMLConstruct[]): HTMLConstruct {
    this.elementStack.unshift('span')
    return this.addStrings(strs)
  }

  p(...strs: HTMLConstruct[]): HTMLConstruct {
    this.elementStack.unshift('p')
    return this.addStrings(strs)
  }

  private addString(str: string): HTMLConstruct {
    this.str = `<${this.elementStack.join('><')}>${str}</${this.elementStack.join('></')}>`
    return this
  }

  private addStrings(strs: HTMLConstruct[]): HTMLConstruct {
    const str = strs.map(s => s.toString()).join('')
    return this.addString(str)
  }

  toString(): string {
    return this.str
  }
}

You can then use the HTMLConstruct class like this:

const html = new HTMLConstruct()

console.log(html.span('foo').toString()) // -> '<span>foo</span>'
console.log(html.div().span('bar').toString()) // -> '<div><span>bar</span></div>'
console.log(html.div().p(
  html.span('bar'),
  html.div().span('baz')
).toString()) // -> '<div><p><span>bar</span><span>baz</span></p></div>'
  • The HTMLConstruct class has a str property that holds the current string being constructed.
  • It also has an elementStack property that holds the elements currently being added to the string.
  • The div(), span(), and p() methods all add the corresponding HTML element to the elementStack and return a new HTMLConstruct object with the current string and elementStack.
  • The addString() method adds the given string to the current string, using the elements in the elementStack to construct the appropriate HTML tags. It then clears the elementStack and returns the new HTMLConstruct object.
  • The addStrings() method is similar to addString(), but it takes an array of HTMLConstruct objects and concatenates their strings together before adding them to the current string.
  • The toString() method simply returns the current string.
  • Related