DOM Binder
The DomBinder is a framework-agnostic utility designed for server-side rendered applications (like ASP.NET Core Razor, PHP, or static HTML).
It connects the ardinIntl translator directly to the DOM using a MutationObserver. This allows for:
- Reactive Language Switching: Changing the locale updates all text instantly without a page reload.
- Dynamic Content: New HTML elements injected via JavaScript (e.g., AJAX, HTMX) are automatically translated.
- SEO Compatibility: It works perfectly with server-rendered initial HTML.
Setup
The library is provided as an IIFE (Immediately Invoked Function Expression). You can include it directly in your browser.
<script src="https://unpkg.com/@ardinsys/intl"></script>Initialization
To start the binder, initialize your translator and pass it to the DomBinder constructor.
<script>
// 1. Define your translations (or load them from the server)
const bundles = {
en: {
messages: { hello: "Hello {name}" },
numberFormats: { default: { minimumFractionDigits: 2 } },
},
hu: {
messages: { hello: "Szia {name}" },
numberFormats: { default: { minimumFractionDigits: 1 } },
},
};
// 2. Create the translator instance
const translator = ardinIntl.createIntl("en", bundles);
// 3. Start the DOM Binder
const binder = new ardinIntl.DomBinder(translator);
</script>Attribute API
The binder uses data- attributes to identify translatable content.
Messages (t)
Use data-t to specify the translation key. Use data-params to pass a JSON string of parameters.
<span data-t="greet">Hello</span>
<span data-t="welcome" data-params='{"name": "John"}'> Hello John </span>Numbers (n)
Use data-n for numeric formatting. The value must be a parsable number.
<span data-n="1234.56">1,234.56</span>
<span data-n="5000" data-fmt="compact">5K</span>Dates (d)
Use data-d for date formatting. Accepts ISO strings or timestamps.
<time data-d="2023-12-25">December 25, 2023</time>
<time data-d="2023-12-25" data-fmt="short">12/25/23</time>Currency (c)
Use data-c for the amount and data-curr for the currency code.
<span data-c="1500.50" data-curr="USD">$1,500.50</span>
<span data-c="-1500.50" data-curr="EUR" data-fmt="accounting">
(€1,500.50)
</span>API Reference
new DomBinder(translator, root?)
Creates a new binder.
- translator: An instance created via
createIntl. - root (optional): The HTMLElement to observe. Defaults to
document.body.
binder.setLocale(locale)
Switches the active language.
- Updates the internal translator state.
- Updates
<html lang="...">. - Refreshes the entire DOM.
// Usage example
document.getElementById("btn-hu").onclick = () => {
binder.setLocale("hu");
};binder.refresh(node?)
Manually triggers a scan. Useful if you are modifying the DOM in a way the MutationObserver might miss (rare).
binder.disconnect()
Stops the observer. Use this during cleanup if your application is a Single Page Application (SPA) navigating away from the view.