if语句
if语句是可以插入到layout里的小代码片段
来帮助layout做决定
当满足某些条件时,可以做某些事情
当不满足某些条件时,可以做其他事情
![![[Pasted image 20240419164941.png]]](https://i-blog.csdnimg.cn/blog_migrate/1f5fcf77cce1ce36ee4f2eece4b66b84.png)
打开post.ejs
post.ejs是网站布局的一部分,用于网站上所有的博客文章
现在有两个博客文档,a.md和b.md
![![[Pasted image 20240419165224.png]]](https://i-blog.csdnimg.cn/blog_migrate/2a4dd2d8c21799389190732a545e460f.png)
a.md作者是ChoSeitaku
![![[Pasted image 20240419165309.png]]](https://i-blog.csdnimg.cn/blog_migrate/b0f7f8e426e9b16aa6c50072ed742bfe.png)
b.md的作者是YiyuKongming
如果想在作者是ChoSeitaku时打印一些代码
不是ChoSeitaku时打印另一些代码
可以使用if语句
结构
<% if( page.author == "ChoSeitaku") { %>
<% } else { %>
<% } %>
可以往里面添加想要执行的代码
<% if( page.author == "ChoSeitaku") { %>
ChoSeitaku is the author, he's the best
<% } else { %>
this author sucks
<% } %>
![![[Pasted image 20240419170044.png]]](https://i-blog.csdnimg.cn/blog_migrate/d0dd045fe0fb03bf61aac5cb272e72f8.png)
![![[Pasted image 20240419170108.png]]](https://i-blog.csdnimg.cn/blog_migrate/686b9a538987f57ad5dc00a84a6cd7a1.png)
if语句还可以用来判断其他东西
<% if(page.author) { %>
ChoSeitaku is the author, he's the best
<% } else { %>
this author sucks
<% } %>
这样就会判断作者是否被设置
![![[Pasted image 20240419170352.png]]](https://i-blog.csdnimg.cn/blog_migrate/97a02225660b2b8f0f2ba15d8f9ffe5c.png)
因为b.md设置了作者
如果删除了b.md的作者,就会输出另一句
forEach语句
![![[Pasted image 20240419170728.png]]](https://i-blog.csdnimg.cn/blog_migrate/e72497e4a2bbdf6774b47c70ef1b468b.png)
打开layout文件夹里的index.ejs文件
现在同样有a和b两篇博客要使用
在网站主页上
比如要显示在post文件夹中的所有的博客文章
可以使用forEach来实现
结构
<% site.posts.forEach(function(post) { %>
<% } ) %>
对于网站上所有的博客文章,要设置一个function函数
向函数传递一个变量post
这个变量post将代表每个循环执行此操作时迭代的单个帖子
这个post将代表Hexo目前正在查看的博客
在循环的内部,可以输入想要执行的操作
比如打印出网站上所有的帖子
![![[Pasted image 20240419171716.png]]](https://i-blog.csdnimg.cn/blog_migrate/966d2612bc01a9b684a453f937991a5f.png)
刷新主页
![![[Pasted image 20240419172017.png]]](https://i-blog.csdnimg.cn/blog_migrate/87c99a55731a5bbf6f21225e7f6257d5.png)
可以添加一个换行标志
![![[Pasted image 20240419172053.png]]](https://i-blog.csdnimg.cn/blog_migrate/afd1d28f7212415abdc08aaf72ebf9bc.png)
![![[Pasted image 20240419172119.png]]](https://i-blog.csdnimg.cn/blog_migrate/fc865572ba3a7894f8e927e3f23f409e.png)
这样就列出了网站中的所有博客
创建一个导航列表
This is index.ejs file
<% site.posts.forEach(function(post) { %>
<li><a href="<%- post.path %>"><%- post.title %></a></li>
<% } ) %>
创建一个列表,将链接放进去,并且在链接的内部放入标题
![![[Pasted image 20240419172431.png]]](https://i-blog.csdnimg.cn/blog_migrate/b3b1481d36e94567a732eb07c9e42d10.png)
<% site.posts.forEach(function(post) { %>
切换site.后面的内容可以访问到网站里的不同实体
- pages
- tags
- categories
forEach会循环遍历所有实体,可以通过引用访问它们的各个变量,通过传递给function()函数的变量
本文介绍了如何在Hexo博客的layout中使用if语句根据作者身份显示不同内容,以及如何使用forEach循环遍历并显示所有博客文章,创建导航列表。
2721

被折叠的 条评论
为什么被折叠?



