Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🐜 Server-oriented customizable templating for JavaScript. Alternative to HTMX and Alpine.js.

License

NotificationsYou must be signed in to change notification settings

hmpl-language/hmpl

Repository files navigation

hmpl

Server-oriented customizable templating for JavaScript

npm-versionminzipped sizecodecovstarsdiscordx.com


Introduction

hmpl is a small template language for displaying UI from server to client. It is based oncustomizable requests sent to the server viafetch and processed into ready-made HTML. The language is syntactically block-based and integrated withJSON5 andDOMPurify. 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...</p>    {{/indicator}}  {{/request}}</div>

Basic usage

importhmplfrom"hmpl-js";consttemplateFn=hmpl.compile(`<div>      <button data-action="increment">Click!</button>      <div>Clicks: {{#request src="/api/clicks" after="click:#btn"}}{{/request}}</div>  </div>`);constclicker=templateFn(({request:{ event}})=>({body:JSON.stringify({action:event.target.getAttribute("data-action")})})).response;document.querySelector("#app").append(clicker);
Explain this!
importhmplfrom"hmpl-js";// Import the HMPL library// Compile an HMPL template with dynamic behaviorconsttemplateFn=hmpl.compile(`<div>      <button data-action="increment">Click!</button>      <!-- This div will update with the click count from /api/clicks -->      <div>Clicks: {{#request src="/api/clicks" after="click:#btn"}}{{/request}}</div>      <!-- Also, you can write in short: {{#r src="..."}}{{/r}} -->  </div>`);// Generate a response handler for the template// In the original object, we will have the following: { response: div, status: 200 }constclicker=templateFn(({request:{ event}})=>({// Send a JSON payload with the action from the button's data attributebody:JSON.stringify({action:event.target.getAttribute("data-action")})})).response;// Append the dynamically generated element to the #app containerdocument.querySelector("#app").append(clicker);

In this example, we create a dynamic clicker component in which, when abutton 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 ofText, but also entire components and even pages!

Usage with DOM

If you need an option without using js, then by connecting the additionalhmpl-dom module you can do this.

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Example</title></head><body><main><templatehmpl><div>          {{#request src="/api/my-component.html"}}            {{#indicator trigger="pending"}}<p>Loading...</p>            {{/indicator}}          {{/request}}</div></template></main><scriptsrc="https://unpkg.com/json5/dist/index.min.js"></script><scriptsrc="https://unpkg.com/dompurify/dist/purify.min.js"></script><scriptsrc="https://unpkg.com/hmpl-js/dist/hmpl.min.js"></script><scriptsrc="https://unpkg.com/hmpl-dom/dist/hmpl-dom.min.js"></script></body></html>

This way, components from the server are mounted into the DOM without having to add them manually. This is great when you want to replace Alpine.js or HTMX in a project.

Request Configuration

Request configuration blocks specify the parameters for server requests that the client will perform when certain events occur.These parameters are provided inside the opening marker{{#request ...}} or{{#r ...}} usingkey=value pairs.

The following attributes are supported:

AttributeTypeExampleDescription
srcstring"/api/test"The request's source URL.
methodstring"get"The HTTP method for the request.
afterstring"click:.target"Event trigger specification.
repeatbooleantrueWhether to repeat the request on future triggers.
intervalnumber1000Interval in milliseconds for repeated requests.
indicatorsHMPLIndicator[][ { trigger: "pending", content: "<p>Loading...</p>" } ]UI indicators for different request states.

Note: Indicators can also be defined via nested{{#indicator}} blocks inside{{#request}}.
autoBodyboolean | HMPLAutoBodyOptions{ formData: true }Configures automatic request body generation.
memobooleantrueEnables caching of the response.
initIdstring | number"id1"Identifier for request initialization.
allowedContentTypesHMPLContentTypes["text/html"]Allowed Content-Type values in the response.
disallowedTagsHMPLDisallowedTags["script" "style" "iframe"]HTML tags to be removed from the response.
sanitizeHMPLSanitizefalseEnables sanitization of the HTML content.

Why HMPL?

Using template language capabilities, you can multiply reduce the size of the application bundle. Full customization of the request based on the modernfetch standard, as well as support for all the functionality necessary for modern work in applications (request indicator, sending by event, automatic generation ofbody for theform, caching) and the syntax of the object in the markup, which requires a minimum number of characters, will help to build interaction with the server and client as efficiently as possible. App sizecomparison (bytes):

App size comparison

Also, HMPL can be a great alternative to popular tools such as HTMX and Alpine.js.

Features

  • Customizable: Send a custom request to the server when receiving the UI
  • Memory Preserving: Reduce file sizes on the client by several times
  • Based on Fetch API: Use a modern standard instead ofXMLHTTPRequest
  • Server-oriented: Work with the server directly through markup and with a little js
  • Generate thousands of DOM nodes from a single template: Work with large components not only on the server but also on the client
  • Simple: Get ready-made UI from the server by writing a couple of lines of familiar object syntax
  • Protected from XSS attacks: Enable incoming server HTML sanitization withDOMPurify and work with it safely
  • Flexible: Can be used in almost any project due to not only working through a script, but also working in files with the.hmpl extension
  • Integrated with JSON5: Flexible writing of objects byspecs as in vanilla js, as well as the reliability of the parser used by millions of people
  • Small bundle size: Lots of functionality in a couple of kilobytes

Installation

hmpl can be installed in several ways, which are described in this section. This tool is a simple javascript file that is connected in the usual way through ascript, or using theimport construct in an environment that supports this (webpack build, parcel build etc.). Also, starting with version2.2.0, the JSON5 module needs to be connected, and starting with version2.2.5, the DOMPurify module also needs to be connected. The first and easiest way is to install using a CDN.

Package Manager

This method involves downloading through npm or other package managers.

npm i hmpl-js

Node.js is required for npm.

Along the path node-modules/hmpl/dist you can find two files that contain a regular js file and a minified one.

CDN

This method involves connecting the file through a third-party resource, which provides the ability to obtain a javascript file from npm via a link.

<scriptsrc="https://unpkg.com/json5/dist/index.min.js"></script><scriptsrc="https://unpkg.com/dompurify/dist/purify.min.js"></script><scriptsrc="https://unpkg.com/hmpl-js/dist/hmpl.min.js"></script><!--  integrity="sha384-..."  crossorigin="anonymous"-->

This resource could be unpkg, skypack or other resources. The examples include unpkg simply because it is one of the most popular and its url by characters is not so long.

Manual download

You can install the package by simplydownloading it as a file and moving it to the project folder.

<scriptsrc="https://unpkg.com/json5/dist/index.min.js"></script><scriptsrc="https://unpkg.com/dompurify/dist/purify.min.js"></script><scriptsrc="./hmpl.min.js"></script>

If, for some reason, you do not need the minified file, then you can download the full file from thislink.

<scriptsrc="https://unpkg.com/json5/dist/index.min.js"></script><scriptsrc="https://unpkg.com/dompurify/dist/purify.min.js"></script><scriptsrc="./hmpl.js"></script>

The non-minified file is larger in size, but it is there as it is with all the formatting.

Ecosystem

vs-code extensionvite-plugin-hmplhmpl-loader

Community support

Thespecification contains main information on how the HMPL template language works. If you have any questions about how HMPL works, you can use the following resources:

  • Github - In the discussion and issues sections you can ask any question you are interested in
  • Discord - You can ask your question in the thematic channel "support"
  • 𝕏 (Twitter) - There is a lot of interesting stuff there, concerning the template language and not only :)

You can also ask your question onStack Overflow and address it in the resources described above.

Contribution

We have aContributing Guide that describes the main steps for contributing to the project.

Thank you to all the people who have already contributed to HMPL, or related projects!

Roadmap

The project has aroadmap where you can see the plans for future development.

Fossa status

FOSSA Status

Licensed underMIT

About

🐜 Server-oriented customizable templating for JavaScript. Alternative to HTMX and Alpine.js.

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp