i have following template for each entry on my website
<div class="image-container">
<img src="images/placeholder.png" alt="Image N">
</div>
<div class="entry-content">
<div class="entry-title">EntryName</div>
<div class="entry-rating">Rating: X</div>
<div class="entry-comment">Comment: Lorem ipsum</div>
</div>
</div>
and i want it to automatically fill each image/title/rating/comment from a JSON file. I would use angular and its for loop to do it but i had problems setting it up on github pages (aswell as nested python scripts).
is there a way to make it work with JS? The entries would be up to 200 entries long
There are probably some complicated ways to do this, and possibly some libraries you would use, but just a simple string template with some tokens to replace works pretty well for something like this.
See the example below.
const template = `<div class="image-container">
<img src="{{imgPath}}" alt="{{imgAlt}}">
</div>
<div class="entry-content">
<div class="entry-title">{{entryTitle}}</div>
<div class="entry-rating">Rating: {{entryRating}}</div>
<div class="entry-comment">Comment: {{entryComment}}</div>
</div>
</div>`;
const data = [
{
imgPath:'https://picsum.photos/id/24/200/200',
imgAlt:'a picture of a book',
entryTitle:'BOOK',
entryRating:'4',
entryComment:'Nice'
},
{
imgPath:'https://picsum.photos/id/23/200/200',
imgAlt:'an image of forks',
entryTitle:'FORKS',
entryRating:'3',
entryComment:'Food!'
},
{
imgPath:'https://picsum.photos/id/2/200/200',
imgAlt:'a laptop at a coffee shop',
entryTitle:'LAPTOP',
entryRating:'5',
entryComment:'I like coffee'
},
];
let htmlString = '';
data.forEach(d => {
let tmplCopy = template;
Object.keys(d).forEach(k => {
const pattern = new RegExp('{{' + k + '}}', 'g');
tmplCopy = tmplCopy.replace(pattern, d[k]);
});
htmlString += tmplCopy;
});
document.getElementById('output-container').innerHTML = htmlString;
<div id="output-container"></div>