A JS DSL for rendering HTML on the client or the server.
The JS HTML Renderer provides a concise and intuitive syntax for writing HTML using JavaScript. You can use the Renderer in order to create a static template and inject dynamic content into it. JS Symbols are used in order to designate where dynamic content will be inserted.
The Renderer's syntax is intuitive and concise e.g.,
const template: Template = doctype()( html()( head()( title()('The Title'), // ⮴ Elements may contain text nodes or other elements. script({ src: 'script.js' })() // ⮴ Attributes are defined using key-value pairs. ), body()( main({ id: 'main-content' })( br(), // ⮴ Void elements lack additional parens for the node collection. p()( $greetings // 🢤 `$greetings` is a JS Symbol. // ⮴ Dynamic content may be injected wherever there is a Symbol. ) ) ) ) );- An intuitive and concise syntax.
- Create your own custom HTML tags (i.e., for Custom Elements).
- Use the prettier of your choice for beautifying your HTML.
npm install js-html-rendererIn this example you will create an HTML document that contains greetings in Esperanto and English.
import { Template, doctype, html, head, body, main, ul, li } from "js-html-renderer";const $greetings = Symbol('greetings');You will use the Symbol created above in order to designate where dynamic content will be inserted.
const template: Template = doctype()( html()( head()( ), body()( main({ id: 'main-content' })( $greetings // ⮴ You will insert an unordered list of greetings here. ) ) ) );You use JavaScript and Renderer HTML elements in order to produce dynamic content. In this example we use Array.prototype.map in order to map the elements of helloWorld into a list of li elements.
const helloWorld = ['Saluton, Mondo!', 'Hello, World!']; const greetings = ul({ id: 'greetings' })( helloWorld.map( (greeting: string, index: number) => li({ id: `greeting-${index}` })(greeting) ) );You use template.render in order to inject the unordered HTML list of greetings created above into the template.
const htmlText = template.render( { [$greetings]: greetings } );console.log(htmlText);<!DOCTYPE html> <html> <head></head> <body> <main id="main-content"> <ul id="greetings"> <li id="greeting-0">Saluton, Mondo!</li> <li id="greeting-1">Hello, World!</li> </ul> </main> </body> </html>Custom HTML tags can be created by binding the name of the tag to the first argument of the Renderer's sigil function. The resulting HTML tag can be used as a Custom Element.
import { $ } from "js-html-renderer";const my_custom_element = $.bind(null, 'my-custom-element');Render the custom element with the class name custom-element and content "Hello, World!" and log it to the console.
console.log(my_custom_element({ class: 'custom-element' })('Hello, World!').render());<my-custom-element class="custom-element">Hello, World!</my-custom-element>