我网站上的每个条目都有以下模板
<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>
我希望它自动填充 JSON 文件中的每个图像/标题/评级/评论。 我会使用 Angular 及其 for 循环来完成此操作,但我在 github 页面(以及嵌套的 python 脚本)上设置它时遇到问题。
有没有办法让它与JS一起工作?条目长度最多为 200 个条目
可能有一些复杂的方法可以做到这一点,并且可能会使用一些库,但只需一个简单的字符串模板和一些要替换的标记就可以很好地完成这样的事情。
请参阅下面的示例。
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>
在 github 页面上,我认为你必须使用纯 css。 它看起来像这样:
let page = document.querySelector("#page");
let entries = [
{ title: "Title1", rating: "Rating1", comment: "comment1" },
{ title: "Title2", rating: "Rating2", comment: "comment2" },
// ...
];
//You will have to get the entries array from your json file using JSON.parse()
entries.forEach((entry) => {
page.innerHTML += `<div class="entry-content">
<div class="entry-title">${entry.title}</div>
<div class="entry-rating">Rating: ${entry.rating}</div>
<div class="entry-comment">Comment: ${entry.comment}</div>
</div>`;
});
<div id="page"></div>