今回は調べたことのメモです。
JavaScriptでBootstrapのCardを作成する方法を調べたら、Stack Overflowにやり方が書いてありました。
具体的にはテンプレートリテラルというJavaScriptの機能を使うんですね。
Stack Overflowのコードを少し改変して貼り付けます。
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap card demo</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> </head> <body> <div class="container-fluid"> <div class="row" id="boardDirectors"></div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <script> const bodList = [ { image: "https://placekitten.com/450/600", name: "First Last", profile: "https://www.google.com", termExp: "2023", title: "Chief Guy", company: "The Company" }, { image: "https://placekitten.com/450/600", name: "First Last", profile: "https://www.google.com", termExp: "2023", title: "Chief Guy", company: "The Company" }, { image: "https://placekitten.com/450/600", name: "First Last", profile: "https://www.google.com", termExp: "2023", title: "Chief Guy", company: "The Company" } ]; function bodTemplate(bod) { return ` <div class="col-md-4 col-lg-3"> <div class="card border-0"> <img src="${bod.image}" class="card-img-top" alt="${bod.name}"> <div class="card-body pl-0"> <h5 class="card-title"><a href="${bod.profile}">${bod.name}</a> <span class="text-right">${bod.termExp}</span></h5> <h6 class="card-title">${bod.title}</h6> <h6 class="card-title"><span class="text-muted font-weight-bold">${bod.company}</span></h6> </div> </div> </div> `; } document.getElementById("boardDirectors").innerHTML = ` ${bodList.map(bodTemplate).join(" ")} `; </script> </body> </html>
今後のためにメモっておきますね。