Skip to content

Better html templating #75

@sc0ttj

Description

@sc0ttj

Steal from "styled components": https://mxstbr.blog/2016/11/styled-components-magic-explained/

when you put in a function to a template literal, we run it, passing in the props of the component

//  `foo`, `bar` and `baz` are any functions 

const myHTML = htmel`
  <div style="${foo}" ${bar}>
      ${baz}
  </div>`;

When htmel encounters functions in a template as above, it should work out their context, run them, convert their output to either CSS or HTML attr syntax (from Objects, if needed), and include the output, if all went well.

TLDR: htmel should provide syntactic sugar for including dynamic styles, HTML attributes and content in templates, by simply by passing in functions to the approperiate place:

// the functions `styles`, `attr` and `body` can return Strings, Numbers, Objects, Elements

const myHTML = htmel`
  <div style="${styles}" ${attrs}>
    ${body}
  </div>`;

Better Array handling:

// This should generate `<li>` elements for each item in the array `myList`

const myHTML = htmel`<ul>$(myList}</ul>`;

and

// This should generate `<source>` elements for each item in the array

const someArray = [
  { srcset: 'file1.png', media: 'max-width: 600px' },
  { srcset: 'file2.png', media: 'min-width: 600px' },
];

const myHTML = htmel`<picture>${someArray}</picture>`;

and

// should add `<td>...</td>`for each item in the array.

const myHTML = htmel`
  <table>
    <tr>${someArray}</tr>
  </table>`;
// This should generate `<tr><td>...</td></tr>` elements for each item in the array

const someArray = [
  { name: 'bob', age: 50 },
  { name: 'amy', age: 50 },
];

const myHTML = htmel`<table>${someArray}</table>`;

...and so on, for other elements which need specific parents/children (see Permitted parents and Permitted content at the bottom of MDN pages about HTML Elements).

For <ul> elements:

Permitted content - Zero or more <li>, <script> and <template> elements.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions