HTML Auto-Generation

Coding less == more

  • Your aim for projects is to make the least amount of static HTML in your projects
  • 75% of your feature should be created using data fetched from API’s
  • To show you a example, I show you all the code behind displaying my announcements


<!-- The only piece of HTML -->
 
<div class="Abox"></div>


<!-- All the JS used to create the rest-->
<script>
    if (location.hostname === "localhost") {
            uri = "http://localhost:8085";
    } else if (location.hostname === "127.0.0.1") {
            uri = "http://127.0.0.1:8085";
    } else {
            uri = "https://flask2.nighthawkcodingsociety.com";
    }
    
    function generateAnnouncements() {
      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");
    
      var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        credentials: 'include',
        redirect: 'follow'
      };
        
      fetch("http://localhost:8085/api/announcements", requestOptions)
        .then(response => response.json())
        .then(result => {
          result.reverse(); // Reverse the order of announcements
          console.log(result);
          for (let i = 0; i < result.length; i++) { // Change to '<'
            var a = result[i];
            createAnnouncement(a.title, a.author, a.tags, a.timestamp, a.body);
          }
        })
        .catch(error => console.log('error', error));
    }
    
    function createAnnouncement(title, author, tags, timestamp, body) {
      var location = document.querySelector(".Abox:last-of-type"); // Correctly target an element
    
      // Check if tags is an array; if not, convert it into an array
      if (typeof tags === 'string') {
        tags = [tags]; // Convert string to array
      } else if (!Array.isArray(tags)) {
        tags = []; // Default to empty array if tags is not an array
      }
    
      var tagElements = tags.map(tag => `<span class="tag">${tag}</span>`).join(''); // Create tag elements
    
      var announcement = `
        <div id="ann">
          <div class="announcement-header">
            <h1 class="announcement-title">${title}</h1>
            <div class="announcement-meta">
              <span class="announcement-author">Author: ${author}</span><br>
              <span class="announcement-timestamp">Timestamp: ${timestamp}</span>
            </div>
          </div>
          <p class="announcement-body">${body}</p>
          <div class="announcement-tags">
            ${tagElements} <!-- Insert the tags here -->
          </div>
        </div>
      `;
    
      location.insertAdjacentHTML('beforeend', announcement); // Use insertAdjacentHTML to add the announcement
    }
    
    
      generateAnnouncements();
    </script>

TODO Talk about when to use Static

TODO Talk about creating static in the beginning auto

TODO Talk about JS

TODO Talk about form building

TODO Talk about Fetch and headers