Jekyll抓取文章中的第一张图片

今天搭了个图片站,是从Wordpress迁移过来的,现在大概有2700篇文章。由于文章太多了,如果要单独给每篇文章设置封面也太大工程量了!强大的Liquid几句代码就解决了这个问题,不必再为每写一篇文章还得单独设置封面而烦恼。 效果可以看咱今天刚搭的大姐姐站:https://mm.too.pub

大姐姐站演示

代码

在需要显示它的位置添加以下代码,一般都是在index.html

{% assign foundImage = 0 %}
{% assign images = post.content | split:"<img " %}
{% for image in images %}
{% if image contains 'src' %}
{% if foundImage == 0 %}
{% assign html = image | split:">" | first %}
{% assign tags = html | split:" " %}
{% for tag in tags %}
{% if tag contains 'src' %}
<img {{ tag }} >
{% endif %}
{% endfor %}
{% assign foundImage = 1 %}
{% endif %}
{% endif %}
{% endfor %}