Rendering HTML from data is a common task in frontend applications. In a single page application this is usually handled by libraries like React.

There will be instances where we need to render a piece of data into a HTML string, in plain Javascript, without using frontend libraries like React. The rendered template string can then be inserted into a DOM element.

Steps

Here is a way to organize data and templates using this approach.

  1. Fetch or gather the template data.
  2. Pass the data to render function.
  3. render function determines which template to render and renders the data.

This approach has the following benefits -

  • Lightweight
  • Organized
  • Seperation of data and template
  • Structure similar to React components

Example data object

Here is an example of the data in the implementation.

const templateName = "hello";

const data = {
  name: "Example Name",
  location: "Example Location",
  // We can add more properties to be passed to the template
};

Render function

/*
  Main render function
*/
function render(templateName, data) {
  switch(templateName) {
    case 'hello':
      return render_hello(data);

    case 'welcome':
      return render_welcome(data);
  }
}

/*
  render hello template
*/
function render_hello(data) {
  return `
    Hello from ${data.name}
    I'm from ${data.location}
  `;
}

// A more concise alternative
// function render_hello({ name, location }) { ... }

/*
  render welcome template
*/
function render_welcome(data) {
  return `
    Welcome to ${data.location}
    Good morning!
  `;
}

// A more concise alternative
// function render_welcome({ location }) { ... }

Using the render function

When we need to render the HTML string, we can use the following.

const helloElement = document.getElementById('hello');
helloElement.innerHTML = render('hello', {
  name: 'Example Name',
  location: 'Example Location'
});

const welcomeElement = document.getElementById('welcome');
welcomeElement.innerHTML = render('welcome', {
  location: 'Example Location'
});

Conclusion

This approach gives a great way to organize the code, including seperation of data and templates. It is also small and perfect for micro-projects for adding dynamic content without a full framework.