HTMX but JSON
Warning
Don't actually use this! I am not a JavaScript programmer and this code cannot be expected to run reliably.
The HTMJ framework is a lightweight JavaScript library designed to simplify the process of fetching data from an API endpoint and rendering it on a webpage using HTML templates.
<script src="https://cdn.jsdelivr.net/gh/g-utils/HTMJ/htmj.js" defer></script>
To use the HTMJ framework, define a <template>
tag with an hx-endpoint
attribute pointing to the API endpoint.
<template hx-endpoint="/api/data">
<div>${data}</div>
</template>
The HTMJ framework uses custom attributes to control its behavior:
Specifies the URL of the API endpoint to fetch data from.
<template hx-endpoint="/api/data"></template>
Defines the elements whose data should be sent to the API. Elements should be specified using a comma-separated list of CSS selectors.
<template hx-endpoint="/api/data" hx-data-sources="#input1, #input2"></template>
Specifies the HTTP method to use when fetching data. If omitted, it defaults to GET
if there are no data sources, or POST
if there are.
<template hx-endpoint="/api/data" hx-method="POST"></template>
Specifies the event that triggers the data fetch. Defaults to onload
. Possible values are onload
, onclick
, onsubmit
, etc. You can define multiple events to listen by seperating them by commas.
<template hx-endpoint="/api/data" hx-event="onchange, onload" hx-event-target="#select"></template>
Specifies a global function to call if an error occurs during the data fetch.
<template hx-endpoint="/api/data" hx-error="handleError"></template>
Defines the CSS selector of the element where the rendered content should be placed. If omitted, defaults to the parent node of the template.
<template hx-endpoint="/api/data" hx-target="#outputDiv"></template>
Specifies the CSS selector of the element that the event listener should be attached to. If omitted, defaults to the target element.
<template
hx-endpoint="/api/data"
hx-event="onclick"
hx-event-target="#button"
></template>
Defines the action to perform on the target element. Possible values are append
, swap
, and update
. Defaults to update
.
<template hx-endpoint="/api/data" hx-action="append"></template>
Used to denote elements that should be populated with nested array data.
<div data-nested-array="nestedData">
<p>${item}</p>
</div>
The HTMJ framework supports nested arrays in the JSON data. The data-nested-array
attribute is used to specify which elements correspond to nested arrays in the JSON data.
Given a JSON response like:
{
"row1": { "name": "Main row" },
"row2": [{ "item": "Nested item 1" }, { "item": "Nested item 2" }]
}
The following template will render the data correctly:
<template hx-endpoint="api/endpoint">
<div class="row">
<span>${row1.name}</span>
<div data-nested-array="row2">
<p>${item}</p>
</div>
</div>
</template>
- acheong08/nameserver - A dead simple server+UI to manage SSL and DNS (WIP).