You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Eleventy的rss.xml enclosure标签中获取文件长度

在Eleventy v3.1.1中为RSS添加带文件大小的enclosure标签

要给RSS的enclosure标签补上图片的字节长度,只需两步:先写一个Eleventy过滤器读取本地图片的文件大小,再在RSS模板里调用这个过滤器填充length属性。


第一步:在eleventy.js中添加获取文件大小的过滤器

导入Node.js的fs/promises和path模块,注册自定义过滤器,根据图片相对路径获取字节数。注意路径拼接要匹配你项目的实际文件结构:

const fs = require('fs/promises');
const path = require('path');

module.exports = function(eleventyConfig) {
  // 异步过滤器:获取文件字节大小
  eleventyConfig.addAsyncFilter('getFileSize', async (imagePath) => {
    // 拼接项目根目录到图片的绝对路径(按需调整目录层级)
    const fullPath = path.join(__dirname, 'src', imagePath);
    try {
      const stats = await fs.stat(fullPath);
      return stats.size;
    } catch (err) {
      // 图片不存在时返回默认值,同时打印警告
      console.warn(`无法读取图片大小: ${fullPath}`, err);
      return 0;
    }
  });
};

第二步:修改RSS模板填充enclosure的length属性

在你的RSS模板(xml文件)里,把enclosure标签的length属性值替换成过滤器调用,直接传入文章的特色图片路径:

<enclosure url="https://my.site/{{ post.data.image }}"
           length="{{ post.data.image | getFileSize }}" 
           type="image/jpeg" />

若你的图片格式不只有jpeg,可以在文章的frontmatter里新增imageType字段,或者额外写一个过滤器根据图片后缀自动判断类型。


修改后的RSS模板核心片段

{%- for post in collections.blog | sortByPubDate | reverse %}
{%- set absolutePostUrl = post.url | htmlBaseUrl(metadata.base) %}
<item>
  <title><![CDATA[{{ post.data.title }}]]></title>
  <link>{{ absolutePostUrl }}</link>
  <description><![CDATA[{{ post.data.excerpt }}]]></description>
  <pubDate>{{ post.data.pubdate | dateToRfc822 }}</pubDate>
  <lastBuildDate>{{ post.date | dateToRfc822 }}</lastBuildDate>
  <dc:creator>{{ metadata.author.name }}</dc:creator>
  <guid>{{ absolutePostUrl }}</guid>
  <enclosure url="https://my.site/{{ post.data.image }}"
             length="{{ post.data.image | getFileSize }}" 
             type="image/jpeg" />
</item>
{%- endfor %}

内容的提问来源于stack exchange,提问作者Chris J. Zähller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 22:12:50