根据 Astro 组件中的数据 json 隐藏或显示 div



我的项目中有site.json,里面有很多数据字符串。如何读取json文件并根据json数据隐藏或显示特定的div?由于我为其创建组件的项目并不都包含对githab的引用或有域名,因此我需要只向那些在json中有此类链接的项目显示svg。

Projects.astro:

---
import ProjectItem from './ProjectItem.astro';
import site from "../data/site.json";
const title = `Projects I’ve been working on`;
const {projects} = site;
---
<section id="projects">
<h3>{title}</h3>
{projects.map((item) => (
<ProjectItem item={item} />
))}
</section>

在ProjectItem.astro中,请注意";div class=";外部";where为外部链接和项目的github创建了两个链接。如果site.json中有我的每个项目的特定信息,我想创建它们。现在这些链接在任何情况下都是创建的,有没有关于githab或域名的信息。我试着用javascript编写一个脚本,但我做不到。

"ProjectItem.astro":

---
const { item } = Astro.props;
---
<div class="project-item-grid">
<div class="project-item-right">
<div class="external">
<a href={item.link} class="link">
<img src="assets/external_link_100.svg" />
</a>
<a href={item.github} class="link">
<img src="assets/github_100.png" />
</a>
</div>
</div>
</div>

这是我的网站.json。我把它缩小了,因为它很大。但请注意";项目";,尤其是项目>链接和项目->github。

{
"skills": {
"comfortable": [
{...}],
"familiar": [
{...}],
},
"projects": [
{
"title": "Title1",
"link": "link1.com",
"github": "link1.github.io"
},
{
"title": "Title2",
"link": "link2.com",
"github":             // information is absent. I think you can put null or "" instead an empty field.
},
"title": "Title3",
"link": ,             // now link's information is absent.
"github": "link3.github.io"           
},
... etc.
]}

我试着用JS:自己解决这个问题

const file = require('../data/site.json');
try {
const data = JSON.parse(file)
} catch(err) {
console.error(err)
}
for (let i=0; i < 3; i++) {
if (data.projects[i].github === null) {
document.getElementById('github').style.display = 'none'
console.log("Catch!");
} else {
console.log("No catch");
}
}

试试这个:

刚刚使用了三元运算符来隐藏null或未定义的值。

---
const { item } = Astro.props;
---
<div class="project-item-grid">
<div class="project-item-right">
<div class="external">
<a style={item.link? ' ':'display:none'} href={item.link} class="link"> 
<img src="assets/external_link_100.svg" />
</a>
<a style={item.github? ' ':'display:none'} href={item.github} class="link">
<img src="assets/github_100.png" />
</a>
</div>
</div>
</div>

最新更新