Tech News
← Back to articles

Show HN: HMPL – Small Template Language for Rendering UI from Server to Client

read original related products more articles

Server-oriented customizable templating for JavaScript

Introduction

hmpl is a small template language for displaying UI from server to client. It is based on customizable requests sent to the server via fetch and processed into ready-made HTML. The language is syntactically block-based and integrated with JSON5 and DOMPurify. Reduce the size of your javascript files and display the same UI as if it was written in a modern framework!

☆ If you find HMPL useful, please consider giving us a star on GitHub! Your support helps us continue to innovate and deliver exciting features.

Example

< div > {{#request src="/api/my-component.html"}} {{#indicator trigger="pending"}} < p > Loading... {{/indicator}} {{/request}}

Basic usage

import hmpl from "hmpl-js" ; const templateFn = hmpl . compile ( `

Clicks: {{#request src="/api/clicks" after="click:#btn"}}{{/request}}
` ) ; const clicker = templateFn ( ( { request : { event } } ) => ( { body : JSON . stringify ( { action : event . target . getAttribute ( "data-action" ) } ) } ) ) . response ; document . querySelector ( "#app" ) . append ( clicker ) ;

Explain this! import hmpl from "hmpl-js" ; // Import the HMPL library // Compile an HMPL template with dynamic behavior const templateFn = hmpl . compile ( `

Clicks: {{#request src="/api/clicks" after="click:#btn"}}{{/request}}
` ) ; // Generate a response handler for the template // In the original object, we will have the following: { response: div, status: 200 } const clicker = templateFn ( ( { request : { event } } ) => ( { // Send a JSON payload with the action from the button's data attribute body : JSON . stringify ( { action : event . target . getAttribute ( "data-action" ) } ) } ) ) . response ; // Append the dynamically generated element to the #app container document . querySelector ( "#app" ) . append ( clicker ) ; In this example, we create a dynamic clicker component in which, when a button is pressed, we will receive the value of the current clicks that will come from the server. The advantage of this approach is that we can take out not only data in the form of Text , but also entire components and even pages!

Usage with DOM

... continue reading