search
HomeWeb Front-endJS TutorialHMPL integration with JSON5

The new version of HMPL has integration with the JSON5 module, which will qualitatively improve the work several times! In this article, I would like to describe in more detail why this was done and why it is necessary.

About JSON5

First of all, it is worth noting the long-standing problem with JSON, which exists in JavaScript, and indeed in almost any other programming language that works with this format.

When working with objects, it seems that everything is convenient and practical. JSON is very convenient and why do we need additional packages at all if there is JSON.parse and JSON.stringify, which will be useful in almost all cases of work? But, let's take this code:

const user = {
    id: 0,
    name: "Tony",
    age: 43,
    hobbies: ["Building anthill"],
};

const jsonString = JSON.stringify(user);

Now, let's output to the console what we got:

console.log(jsonString);

// output - {"id":0,"name":"Tony","age":43,"hobbies":["Building anthill"]}

We got a seemingly ordinary string, which can easily be translated back with parsing and everything is cool, only this string takes up "a lot" of space on the disk, and also imagine if you write all this manually, and not in JavaScript through a convenient object? Yes, this is the main problem with this functionality.

HMPL integration with JSON5

If we take the same JavaScript object and write it normally in a string, then JSON.Parse will not parse it, giving an error:

const userString = `{
    id: 0,
    name: "Tony",
    age: 43,
    hobbies: ["Building anthill"],
}`

JSON.parse(userString);

// Uncaught SyntaxError: Expected property name or '}' in JSON at position 6 (line 2 column 5)
//   at JSON.parse (<anonymous>)
</anonymous>

To fix this, we will have to adjust the string to the format. To do this, we will have to manually constantly write double quotes near the object properties. We will always have to not put a comma at the end, not write comments in the string like in JS, etc. We kind of get convenient functionality, but if we consider it as something that we will write manually, then it is simply incredibly inconvenient, because everyone is used to writing a JS object manually, and not JSON.

So, the JSON5 module allows you to write strings almost like in JS and not have the problems described above:

import JSON5 from "json5";

const userString = `{
    id: 0,
    name: "Tony",
    age: 43,
    hobbies: ["Building anthill"],
}`

JSON5.parse(userString);

/*
{
    id: 0,
    name: "Tony",
    age: 43,
    hobbies: ["Building anthill"],
};
*/

Even the slogan of the module itself says: "JSON5 – JSON for Humans".

Of course, the problem may seem insignificant at first glance, but only until it becomes a daily issue. It's okay to correct quotes once, remove a comma, but doing it manually every day is incredibly tedious. Therefore, as one of the modules that solves this problem, it is the best fit for all of this.

You can even remember not abstract examples, but specific ones that are used in work. Have you ever configured a configuration file when working with some code assemblers or something else? The same linters, prefixers, module builders, various text editors - all this works, including through JSON.

And, usually, such files are filled manually by users. And, now there is a need to parse such moments, for example, here is an example of a config:

const user = {
    id: 0,
    name: "Tony",
    age: 43,
    hobbies: ["Building anthill"],
};

const jsonString = JSON.stringify(user);

And, such an object also needs to be parsed on the application side. These parameters can be any and in any format, as well as with comments and other jokes. Manually writing such a parser is not cost-effective, and simply unnecessary.

About the benefits for HMPL

The HMPL module is based on extended HTML markup, to which we pass objects, and at the output we receive a ready component from the server. Let's take an example of the code:

console.log(jsonString);

// output - {"id":0,"name":"Tony","age":43,"hobbies":["Building anthill"]}

Before version 2.2.0, the module was based on JSON.parse, so this whole thing was completely inconvenient. The stringify function was introduced, which somehow bypassed this point, but it's clear that it's still in separate ones .hmpl files js code will be problematic to write. Here is an example of stringify and a file:

const userString = `{
    id: 0,
    name: "Tony",
    age: 43,
    hobbies: ["Building anthill"],
}`

JSON.parse(userString);

// Uncaught SyntaxError: Expected property name or '}' in JSON at position 6 (line 2 column 5)
//   at JSON.parse (<anonymous>)
</anonymous>

mail.hmpl:

import JSON5 from "json5";

const userString = `{
    id: 0,
    name: "Tony",
    age: 43,
    hobbies: ["Building anthill"],
}`

JSON5.parse(userString);

/*
{
    id: 0,
    name: "Tony",
    age: 43,
    hobbies: ["Building anthill"],
};
*/

Therefore, I think that integration with JSON5 is the best way to make sites even faster and smaller in size. Now, it's generally super convenient, because you can just copy an object from JavaScript and paste it into an HTML file.


By the way, the module repository itself can be found here. It will be cool if you rate it with a star ☆ if you think this module is useful :)

HMPL integration with JSON5 hmpl-language / hmpl

? Server-oriented customizable templating for JavaScript

HMPL integration with JSON5

HMPL integration with JSON5 HMPL integration with JSON5 HMPL integration with JSON5 HMPL integration with JSON5

HMPL integration with JSON5 HMPL integration with JSON5

Server-oriented customizable templating for JavaScript

Website • Documentation • Demo Sandbox • Examples
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 object-based and integrated with JSON5. Reduce the size of your javascript files and display the same UI as if it was written in a modern framework.

Usage

import hmpl from "hmpl-js";

const templateFn = hmpl.compile(
  `<div>
      <button data-action="increment">
<div>
<div>
    <svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24"><title>Enter fullscreen mode</title>
    <path d="M16 3h6v6h-2V5h-4V3zM2 3h6v2H4v4H2V3zm18 16v-4h2v6h-6v-2h4zM4 19h4v2H2v-6h2v4z"></path>
</svg>

    <svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24"><title>Exit fullscreen mode</title>
    <path d="M18 7h4v2h-6V3h2v4zM8 9H2V7h4V3h2v6zm10 8v4h-2v-6h6v2h-4zM8 15v6H6v-4H2v-2h6z"></path>
</svg>

</div>
</div>
</button>
</div>
<div>
<h2 id="Why-HMPL">Why HMPL?</h2>

</div>

<p dir="auto">Using…</p>

View on GitHub


The above is the detailed content of HMPL integration with JSON5. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor