miatech
miatech

Reputation: 2278

output javascript template to html page inside a row div

I have json api which is a list of books with their properties: title, author, etc.. I need to output the data formatted to html. I'm using es6 backtics for this and javascript templating. But the problem I'm encountering is that the output is not one iterationg to html page, but every two iteration. every single object from json goes into an html card. But my page requires two cards per row. so I need to insert an opening row div every two iteration and an closing row div every two iteration, so that in between the opening row and closing div I have the two cards. I first thought to put my template in a variable, but that didn't work. Second I put it in a function with return statement. this time work, but I can properly insert the row tags... could someone suggest proper easier way to do this? thanks here's the index.html page. the two cards are in one row. I don't know before hand how many card I will need. the output will be posted to list-ouput id.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Book Finder</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <div id="title" class="center">
        <h1 class="text-center mt-5">Book Finder</h1>
        <div class="row">
          <div id="input" class="input-group mx-auto col-lg-6 col-md-8 col-sm-12">
            <input id="search-box" type="text" class="form-control"  placeholder="Search Books!...">
            <button id="search" class="btn btn-primary" onclick="">Search</button>
        </div>
        </div>
      </div>
      <div class="book-list" >
        <h2 class="text-center">Search Result</h2>
        <div id="list-output" class="">
          <div class="row">
            <!-- card  -->
            <div class="col-lg-6">
              <div class="card" style="">
                <div class="row no-gutters">
                  <div class="col-md-4">
                    <img src="" class="card-img" alt="...">
                  </div>
                  <div class="col-md-8">
                    <div class="card-body">
                      <h5 class="card-title">Book Title</h5>
                      <p class="card-text">Author</p>
                      <p class="card-text"><small class="text-muted">Publisher: </small></p>
                      <a href="${bookLink}" class="btn btn-secondary">More Info</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- card  -->
            <div class="col-lg-6">
              <div class="card" style="">
                <div class="row no-gutters">
                  <div class="col-md-4">
                    <img src="" class="card-img" alt="...">
                  </div>
                  <div class="col-md-8">
                    <div class="card-body">
                      <h5 class="card-title">Book Title</h5>
                      <p class="card-text">Author</p>
                      <p class="card-text"><small class="text-muted">Publisher: </small></p>
                      <a href="${bookLink}" class="btn btn-secondary">More Info</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </div>

        </div>
      </div>
    </div>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/style.css">
    <!-- <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> -->
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script src="js/index.js"></script>
  </body>
</html>

$(document).ready(function() {
      var item, tile, author, publisher, bookLink, bookImg;
      var outputList = document.getElementById("list-output");
    
      //listener for search button
      $("#search").click(function() {
         $("#title").animate({'margin-top': '5px'}, 1000);
         // $(".book-list").css("visibility", "visible");
         var searchData = $("#search-box").val();
         if(searchData === "") {
           // dsiplayErr();
         } else {
           console.log(searchData);
           $.get("https://www.googleapis.com/books/v1/volumes?q="+searchData, function(response) {
              for (var i = 0; i < response.items.length; i++) {
                item = response.items[i];
                title = item.volumeInfo.title;
                author = item.volumeInfo.authors;
                publisher = item.volumeInfo.publisher;
                bookLink = item.selfLink;
                bookImg = item.volumeInfo.imageLinks.thumbnail;
                // in production code, item.text should have the HTML entities escaped.
    
                if( (i+2) % 2 != 0) {
                  console.log("odd")
                  outputList.innerHTML += `<div class="row">`;
                }
                outputList.innerHTML += formatOutput(title, author, bookLink, bookImg);
                if((i+2) % 2 == 0) {
                  console.log("even")
                  outputList.innerHTML += `</div>`;
                }
                console.log(outputList.innerHTML);
              }
            });
          }
       });
    
    });
    
    
    
    function formatOutput(title, author, publisher, bookLink, bookImg) {
      // console.log(title + ""+ author +" "+ publisher +" "+ bookLink+" "+ bookImg)
      var htmlCard1 = `<div class="col-lg-6">
        <div class="card" style="">
          <div class="row no-gutters">
            <div class="col-md-4">
              <img src="${bookImg}" class="card-img" alt="...">
            </div>
            <div class="col-md-8">
              <div class="card-body">
                <h5 class="card-title">${title}</h5>
                <p class="card-text">Author: ${author}</p>
                <p class="card-text"><small class="text-muted">Publisher: ${publisher}</small></p>
              </div>
            </div>
          </div>
        </div>
      </div>`
      return htmlCard1;
    }

Upvotes: 0

Views: 329

Answers (1)

U.Y.
U.Y.

Reputation: 779

I removed few lines which i thought were unnecessary but you can add them back if you want. Following code should be working as you expected

       $(document).ready(function () {
            var item, tile, author, publisher, bookLink, bookImg;
            var outputList = $("#list-output");

            //listener for search button
            $("#search").click(function () {
                var searchData = $("#search-box").val();
                if (searchData === "") {
                    // dsiplayErr();
                } else {
                    console.log(searchData);
                    $.get("https://www.googleapis.com/books/v1/volumes?q=" + searchData, function (response) {
                        for (var i = 0; i < response.items.length; i++) {
                            item = response.items[i];
                            title = item.volumeInfo.title;
                            author = item.volumeInfo.authors;
                            publisher = item.volumeInfo.publisher;
                            bookLink = item.selfLink;
                            bookImg = item.volumeInfo.imageLinks.thumbnail;
                            // in production code, item.text should have the HTML entities escaped.
                            var html;
                            if ((response.items.length % 2 != 0) && (i == response.items.length - 1)) {
                                html = "";
                                html += "<div class='row'>";
                                html += formatOutput(title, author, publisher, bookLink, bookImg);
                                html += "</div>";
                                outputList.append(html);
                            }
                            else {
                                if (i % 2 == 0) {
                                    html = "";
                                    html += "<div class='row'>";
                                }

                                html += formatOutput(title, author, publisher, bookLink, bookImg);

                                if (i % 2 != 0) {
                                    html += "</div>";
                                    outputList.append(html);
                                }
                            }
                        }
                    });
                }
            });

        });



        function formatOutput(title, author, publisher, bookLink, bookImg) {
            // console.log(title + ""+ author +" "+ publisher +" "+ bookLink+" "+ bookImg)
                var htmlCard1 = `<div class="col-lg-6">
                <div class="card" style="">
                  <div class="row no-gutters">
                    <div class="col-md-4">
                      <img src="${bookImg}" class="card-img" alt="...">
                    </div>
                    <div class="col-md-8">
                      <div class="card-body">
                        <h5 class="card-title">${title}</h5>
                        <p class="card-text">Author: ${author}</p>
                        <p class="card-text"><small class="text-muted">Publisher: ${publisher}</small></p>
                        <a href="${bookLink}" class="btn btn-secondary">More Info</a>
                      </div>
                    </div>
                  </div>
                </div>
              </div>`
            return htmlCard1;
        }

Upvotes: 1

Related Questions