zspecza / common-tags

🔖 Useful template literal tags for dealing with strings in ES2015+

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support nested html

opened this issue · comments

I've been learning about tagged templates and I discovered common-tags. It's so useful -- many thanks for it!

I was hoping that html might be able to handle nested, multi-line sections, such as you might produce with another html tagged literal. Then you could compose html and have the indenting magically work. But that doesn't seem to be the case.

Here's a test case. Would supporting something like this be at all feasible?

const { html } = require("common-tags");

test("renders nested HTML", () => {
  const fruits = ["apple", "banana", "kiwi"];
  const expected = `<!DOCTYPE html>
<html lang="en">
  <body>
    <ul>
      <li>
        <div>apple</div>
      </li>
      <li>
        <div>banana</div>
      </li>
      <li>
        <div>kiwi</div>
      </li>
    </ul>
  </body
</html>`;

  function renderFruit(fruit) {
    return html`
      <li>
        <div>${fruit}</div>
      </li>`;
  }

  const actual = html`
    <!DOCTYPE html>
    <html lang="en">
      <body>
        <ul>
          ${fruits.map(renderFruit)}
        </ul>
      </body>
    </html>`;

  expect(actual).toBe(expected);
});

I think it is feasible. Since I've been working today on refurbishing common-tags to improve composability, I might sneak in some other improvements. Sorry for not answering for so long.

The problem is in the inlineArrayTransformer part. It's not too difficult to code, but the decisions to be made are hard. Once I wrap my head around this the html tag will just work.

I'd be interested in this functionality as well. I'm storing some JSX in variables, then interpolating it with template literals. Having the indention work out of the box would be awesome!

I think I managed to do just that. This will be released in the upcoming next version.