'How to create template or placeholder in html and add them dynamically to the body?

I want to create a forum in html. As you have guessed I am new to web dev.

Let's say there is a template for messages posted by the users:

<div id="message">
    <h3>#name of the user</h3>
    <p>#message</p>
</div>

I wish to populate this template with the user's name and the message and then dynamically add it to the main body when the user posts it.

However as I told you I am very new to web development. I am not sure how to do this. All I need is your guideline and ideas. Maybe point me toward appropriate tutorial and references.



Solution 1:[1]

You can use Template Literals and just interpolate name and msg inside template.

let template  = document.querySelector('div#message');

function createMessage(name,msg){
  return (
    `<div id="message">
    <h3>${name}</h3>
    <p>${msg}</p>
    </div>`
  
  )
}


let data = [{
  name:"name 1",
  message:"message 1",
},

{
  name:"name 2",
  message:"message 3",
},
{
  name:"name 3",
  message:"message 3",
},

]


let str = data.map(x => createMessage(x.name,x.message)).join('');

document.body.insertAdjacentHTML("afterend",str)

Solution 2:[2]

You can use format unicorn to do this like stackExchange does, example:

Your Html:

    <div id="messageLoader">

    </div>

  <script type="text/template" id="templateMessage">
    <h2>{title}</h2>
    <p>{message}</p>
    <br>
    <span><Strong>{sign}</strong><span>
  </script>

Your script:

String.prototype.formatUnicorn =  function () {
      "use strict";
      var str = this.toString();
      if (arguments.length) {
          var t = typeof arguments[0];
          var key;
          var args = ("string" === t || "number" === t) ?
              Array.prototype.slice.call(arguments)
              : arguments[0];

          for (key in args) {
              str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
          }
      }

      return str;
  };
  var jsonMessage = {title:"Custom Template With Form Unicorn",message:"Stack Overflow Rocks bae !!",sign:"Stan Chacon"};
  let myFirstUnicornTemplate = document.getElementById("templateMessage").text;
  var template = myFirstUnicornTemplate.formatUnicorn(jsonMessage);
  document.getElementById("messageLoader").innerHTML = template;

EDIT: fun fact you can use it here in stack overflow just copy and paste this on console :

"Hello {name}, welcome to StackOverflow {emoji}".formatUnicorn({name:"User",emoji:"=)"});

Or try the snippet:

  String.prototype.formatUnicorn =  function () {
      "use strict";
      var str = this.toString();
      if (arguments.length) {
          var t = typeof arguments[0];
          var key;
          var args = ("string" === t || "number" === t) ?
              Array.prototype.slice.call(arguments)
              : arguments[0];

          for (key in args) {
              str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
          }
      }

      return str;
  };

var x = "Hello {name}, welcome to StackOverflow {emoji}".formatUnicorn({name:"User",emoji:"=)"});
console.log(x);

Hope it helps =)

Solution 3:[3]

If you're using javascript you can manipulate the content of an html tag like this:

document.getElementById("yourhtmltagid").innerHTML = "#message";

you can learn the basics on your own:

https://www.w3schools.com/jsref/prop_html_innerhtml.asp

Solution 4:[4]

Ignoring the notion of a forum in HTML (see comments on original post), Web Components provide this functionality and have been gaining support since the beginning of 2019.

Web Components include <slot>s that can be used as placeholders in <template>s, custom elements that can define values for those slots, and shadow DOMs to display the result (see Using templates and slots).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Bobbey
Solution 4 Jeremy Harnois