由hexo-generator-feed生成的 Atom 和 RSS2 文件中,文章摘要会包含原文中的 HTML 标签,这显然不合理。因此,我们需要通过自定义模板来对文章内容进行处理。
- 如果你还不知道如何使用自定义模板,请参考下面这篇文章:
- 打开模板文件,找到下列这段组装文章摘要的部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| {% if post.description %} <summary type="html">{{ post.description }}</summary> {% elif post.intro %} <summary type="html">{{ post.intro }}</summary> {% elif post.excerpt %} <summary type="html">{{ post.excerpt }}</summary> {% elif post.content %} {% set short_content = post.content.substring(0, config.feed.content_limit) %} {% if config.feed.content_limit_delim %} {% set delim_pos = short_content.lastIndexOf(config.feed.content_limit_delim) %} {% if delim_pos > -1 %} <summary type="html">{{ short_content.substring(0, delim_pos) }}</summary> {% else %} <summary type="html">{{ short_content }}</summary> {% endif %} {% else %} <summary type="html">{{ short_content }}</summary> {% endif %} {% endif %}
|
post.content是文章的完整内容,包含 HTML 标签。可以看到,插件原本的模板只是将内容截取了一定长度,没有对 HTML 标签做任何处理。
- 修改这部分内容,先去除 HTML 标签,再截取文本长度。
利用 Nunjucks 的链式过滤器调用内置函数striptags和truncate实现目标。
由于content_limit_delim这个参数几乎用不上,所以我没怎么修改这部分内容,有需要的朋友自行参照下列写法来修改即可。
post.description和post.intro目前还不清楚会在哪里用到,所以对于我个人而言,这两部分也无需修改。
_custom_atom.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| {% if post.description %} <summary type="html">{{ post.description }}</summary> {% elif post.intro %} <summary type="html">{{ post.intro }}</summary> {% elif post.excerpt %} <summary type="html">{{ post.excerpt | striptags }}</summary> {% elif post.content %} {% if config.feed.content_limit_delim %} {% set short_content = post.content.substring(0, config.feed.content_limit) %} {% set delim_pos = short_content.lastIndexOf(config.feed.content_limit_delim) %} {% if delim_pos > -1 %} <summary type="html">{{ short_content.substring(0, delim_pos) }}</summary> {% else %} <summary type="html">{{ short_content }}</summary> {% endif %} {% else %} <summary type="html">{{ post.content | striptags | truncate(config.feed.content_limit) }}</summary> {% endif %} {% endif %}
|
_custom_rss2.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| {% if post.description %} <description>{{ post.description }}</description> {% elif post.intro %} <description>{{ post.intro }}</description> {% elif post.excerpt %} <description>{{ post.excerpt | striptags }}</description> {% elif post.content %} {% if config.feed.content_limit_delim %} {% set short_content = post.content.substring(0, config.feed.content_limit) %} {% set delim_pos = short_content.lastIndexOf(config.feed.content_limit_delim) %} {% if delim_pos > -1 %} <description>{{ short_content.substring(0, delim_pos) }}</description> {% else %} <description>{{ short_content }}</description> {% endif %} {% else %} <description>{{ post.content | striptags | truncate(config.feed.content_limit) }}</description> {% endif %} {% endif %}
|
- 大功告成
执行 hexo clean 和 hexo generate 后,在 public 文件夹内检查下生成的 Feed 文件是否正确吧。
本作品由 小橘猫 于 2025-11-04 16:16:01 发布
除特别声明外,本站作品均采用
CC BY-NC-SA 4.0 许可协议,转载请注明来自
嗷呜星球