Home Made Javascript MVC Explained Part 1

Created: 10 September 2020  Modified:

This is the start of a series of articles showing how to implement a simple MVC framework in ECMAScript. ECMAScript is the official specification for Javascript. We will start by working through a small example of how to render a template. We will write a method that will take JSON data and merge it with an html template. Then we will display the result.

First lets look into our HTML. Below is a basic HTML page without any Javascript. This will provide the framework around which we will build our example. The DIV tag with id of contentHolder (DIV#contentHolder) provides the location where we will display our rendered content. The SCRIPT tag with id of theTemplate (SCRIPT#theTemplate) is where we define our template for the content that will be placed in DIV#contentHolder. The ###REPLACE_ME1### is a marker indicating that it should be replaced with data. Using the triple pound/hash as a prefix and suffix around text will indicate that text should be replaced with data. You can have as many replacement markers in a template as you like.

HTML Page

<html>
  <head>
  </head>
  <body>
    This is a test.  Rendered content is shown below inside the square.<br/><br/>
   <div id="contentHolder" style="border-width: .2em; border-style: solid;">

   </div>
  </body>
      <script type="text/html" id="theTemplate" >
        ###REPLACE_ME1### ###REPLACE_ME2###
        <ul>
          <li>Mineral?</li>
          <li>Vegetable?</li>
          <li>Animal?</li>
        </ul>
      </script>
</html>

Now the next step we need is to define a Javascript function that will take JSON data and merge it with the contents of SCRIPT#theTemplate. This function requires two parameters. The first parameter will be a JSON object. The second parameter will be a string containing our template. The first line defines a Regular Expression object that will be used to replace any text that is surround by the triple pound/hash. The second line uses a call to the String.replace method. The replace method takes a regular expression and data with which to replace matches of the regular expression. Now this line of code looks a little messy because we are passing a callback function in place of our data. This callback function takes the regular expression match and uses it as the key to the JSON data object. Using our template above the regular expression will find the text ###REPLACE_ME1#### and will strip off the pound/hash characters to return REPLACE_ME which will be used as the key in the JSON data object. The rest of the function makes sure if no data is found in the JSON data object that we return a String containing no characters.

Render Template Javascript Function

        function renderTemplate (jsonData, htmlTemplate) {
	    var regex = new RegExp(/###([a-zA-Z0-9_]*)###/ig);
	    return htmlTemplate.replace(regex, function(match, jsonKey) {
	               return (typeof jsonData[jsonKey] !== 'undefined') ? jsonData[jsonKey] : ""
		   });
	}	

Our next step is to provide some JSON data and get references to the objects we need to manipulate. HTML is represented by a Document Object Model (DOM) in the browser. The first line defines a JSON data object directly in Javascript. Which is a plain old Javascript object using key value pairs. Next we get a reference to the element containing our HTML template. This is followed by obtaining a reference to where we will place our rendered template. Now we call our renderTemplate method passing in our data and template. This returns the rendered template and we place it inside our element where we want to display the rendered content.

Define our data and get objects.

        var data = { "REPLACE_ME1" : "Hiya and Hello!",  
                     "REPLACE_ME2" : "I am rendered content.  What are you?" };
        var template = document.getElementById("theTemplate").innerText;

        var contentHolder = document.getElementById("contentHolder");
        var renderedResult = renderTemplate(data, template );

        contentHolder.innerHTML = renderedResult;

Below is the entirety of our example code.

HTML Page combining JSON and a Template

<html>
  <head>
  </head>
  <body>
    This is a test.  Rendered content is shown below inside the square.<br/><br/>
   <div id="contentHolder" style="border-width: .2em; border-style: solid;">

   </div>
  </body>
      <script type="text/html" id="theTemplate" >
        ###REPLACE_ME1### ###REPLACE_ME2###
        <ul>
          <li>Mineral?</li>
          <li>Vegetable?</li>
          <li>Animal?</li>
        </ul>
      </script>
      <script>
        function renderTemplate (jsonData, htmlTemplate) {
	    var regex = new RegExp(/###([a-zA-Z0-9_]*)###/ig);
	    return htmlTemplate.replace(regex, function(match, jsonKey) {
	               return (typeof jsonData[jsonKey] !== 'undefined') ? jsonData[jsonKey] : ""
		   });
	}	
	

        var data = { "REPLACE_ME1" : "Hiya and Hello!",  
                     "REPLACE_ME2" : "I am rendered content.  What are you?" };
        var template = document.getElementById("theTemplate").innerText;

        var contentHolder = document.getElementById("contentHolder");
        var renderedResult = renderTemplate(data, template );

        contentHolder.innerHTML = renderedResult;
      </script>
</html>
tags: ecmascript - javascript - mvc - html - template
   Less Is More