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

Eleventy中单个Shortcode调用其他Shortcode的实现方法咨询

回答:Eleventy Shortcode 调用其他 Shortcode 的实现方案

当然可以!Eleventy 完全支持在一个 Shortcode 里调用另一个,甚至可以触发多个不同的 Shortcode。针对你给出的具体场景,这里有两种简单可行的实现方式:

方法一:提取独立渲染函数(同步场景首选)

这种方式把 Shortcode 的渲染逻辑抽成独立函数,让多个 Shortcode 可以复用,代码结构更清晰:

  1. 先把 img 的渲染逻辑定义成单独的函数:
// 独立的图片渲染函数
const renderImg = (path) => {
  return `<img src="${path}">`;
};
  1. 分别注册 img 和 card Shortcode:
// 注册 img Shortcode
eleventyConfig.addNunjucksShortcode("img", renderImg);

// 注册 card Shortcode,直接调用 renderImg 函数
eleventyConfig.addNunjucksShortcode("card", function(imgPath) {
  return `<div class="card"> ${renderImg(imgPath)} </div>`;
});

这样当你在模板里写 {% card 'path-to-img.jpg' %} 时,就会直接渲染出你想要的结果:

<div class="card"> <img src="path-to-img.jpg"> </div>

方法二:使用 Eleventy 的 renderShortcode API(灵活适配异步场景)

如果你不想抽离函数,或者涉及到异步 Shortcode,可以用 Eleventy 提供的 this.renderShortcode 方法直接调用已注册的 Shortcode:

// 注册 img Shortcode(保持你的原有代码)
eleventyConfig.addNunjucksShortcode("img", function(path) {
  return `<img src="${path}">`;
});

// 注册异步的 card Shortcode
eleventyConfig.addNunjucksAsyncShortcode("card", async function(imgPath) {
  // 调用已注册的 img Shortcode,传入参数数组
  const imgHtml = await this.renderShortcode("img", [imgPath], {});
  return `<div class="card"> ${imgHtml} </div>`;
});

使用这种方式时,模板里的调用要加上 await:

{% await card 'path-to-img.jpg' %}

这种方法的优势是不需要改动原有 Shortcode 的定义,直接通过 API 调用,适合需要组合多个不同 Shortcode 的复杂场景。


内容的提问来源于stack exchange,提问作者Oleksii Binetskyi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:12:34