Placeholders don't fill themselves

A reader wrote in with HTML, CSS, and JavaScript that wasn't doing what he expected: his markup contained placeholders, his script held the matching data, and he assumed the data would flow into the placeholders on its own.

Anyone with a bit of web experience can spot the gap immediately, but it's worth looking at the situation from his side and then at fixes that are about as simple as the original problem.

The markup

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
  <link rel="stylesheet" href="test.css">
  <script src="data.js"></script>
</head>
<body>
  <section>
    <div>{company_name}</div>
  </section>
</body>
</html>

The script

var company_data = {
  "{company_name}" : "SOME COMPANY",
};

Valid code, wrong assumption

Nothing here is broken. The two files are wired together correctly, the code runs, and the page simply displays {company_name}. The expectation was that SOME COMPANY would appear in its place, pulled from the JavaScript file.

That expectation is essentially templating: hand over an object whose keys match the placeholders in the HTML, and have the HTML contents swapped for the values. Raw web technology doesn't behave that way.

The smallest possible fix

For this specific case, showing the right company name takes one extra line in the JavaScript: select the element from the DOM and replace its content with the data.

var company_data = {
  "{company_name}": "SOME COMPANY"
};

document.querySelector("div").innerHTML = company_data["{company_name}"];

It isn't reusable or resilient, but it also avoids over-thinking or over-tooling a problem this small.

Real templating options

There are hundreds of ways to solve this properly. A few, off the top of the head:

  • A templating language such as Handlebars or Mustache
  • A static site generator, for example Eleventy, which uses Liquid by default
  • An HTML <template> element plus your own script to consume it
  • A Web Component
  • A back-end language, or something like Nunjucks to process ahead of time
  • A preprocessor such as Pug

As a general preference, doing the templating on the server or at build time is ideal — why touch the DOM when you don't have to? Setting that advice aside, though, the client-side approach with Handlebars works like this:

CSS-Tricks star logo

Ads are self-hosted