Suppose you have a variable, message
, that you want to be displayed, along with today’s day, in the markup generated by Dompiler. You can do so with this JavaScript (which you’ll place in a file called app.js
):
// Import Dompiler.
import Dompiler from "../../library/dompiler.js";
// Initialize Dompiler.
let {
compile
} = new Dompiler().withBinding();
// Variables.
let message = "Hello World.",
date = new Date().toLocaleDateString();
// Compile markup string into a document fragment.
let markup = `
<div>
${message} The date is ${date}.
</div>
`,
compiled = compile(markup);
// Append compiled markup to container.
let container = document.querySelector(".example-container");
container.appendChild(compiled);
Note that this is really just using template literal interpolation syntax to inject the variables into the string. This is an example of how Dompiler works in tandem with plain JavaScript. You can read about template literals and interpolation here: A Guide to JavaScript Template Literals
The markup would look something like this:
<!DOCTYPE html>
<html>
<head>
<title>Dompiler Example</title>
</head>
<body>
<div class="example-container"></div>
<script src="app.js" type="module"></script>
</body>
</html>
You can see a live example here: