跳转到导航 跳转到主要内容
CNB版本
社区版
cnb.cool
国外版
cnb.build
2025/12/29

图像(短代码)

本页大纲
Eleventy 图像使用类型
  • 图像 HTML 转换: 推荐—从这个开始!这是最容易配置的,并且与所有模板语法兼容。

We can use the Image JavaScript API and wire it up to a Universal Shortcode.

Asynchronous Shortcode

The examples below require an async-friendly shortcodes (works in Nunjucks, Liquid, JavaScript, and WebC).



Configuration

eleventy.config.js
import Image from "@11ty/eleventy-img";

export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt, widths = [300, 600], sizes = "") {
return Image(src, {
widths,
formats: ["avif"], // 仅使用 AVIF 格式
returnType: "html", // new in v6.0
htmlOptions: { // new in v6.0
imgAttributes: {
alt, // required, though "" works fine
sizes, // required with more than one width, optional if single width output
loading: "lazy", // optional
decoding: "async", // optional
}
}
});
});
};
const Image = require("@11ty/eleventy-img");

module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt, widths = [300, 600], sizes = "") {
return Image(src, {
widths,
formats: ["avif"], // 仅使用 AVIF 格式
returnType: "html", // new in v6.0
htmlOptions: { // new in v6.0
imgAttributes: {
alt, // required, though "" works fine
sizes, // required with more than one width, optional if single width output
loading: "lazy", // optional
decoding: "async", // optional
}
}
});
});
};

More about Shortcodes

Template Usage

Now you can use the image shortcode in your templates and the appropriate HTML will be generated for you (based on your specified Image options).

{% image "cat.jpg", "photo of my tabby cat" %}
{% image "cat.jpg", "photo of my tabby cat", "(min-width: 30em) 50vw, 100vw" %}

在 Liquid 模板中,参数之间的逗号是可选的

{% image "cat.jpg", "photo of my tabby cat" %}
{% image "cat.jpg", "photo of my tabby cat", "(min-width: 30em) 50vw, 100vw" %}

在 Nunjucks 模板中,参数之间的逗号是必需的

export default function() {
	let img1 = await this.image("cat.jpg", "photo of my tabby cat");
	let img2 = await this.image("cat.jpg", "photo of my tabby cat", "(min-width: 30em) 50vw, 100vw");
    return `${img1}
${img2}`;
};
module.exports = function() {
	let img1 = await this.image("cat.jpg", "photo of my tabby cat");
	let img2 = await this.image("cat.jpg", "photo of my tabby cat", "(min-width: 30em) 50vw, 100vw");
    return `${img1}
${img2}`;
};

If you want to use Eleventy Image in WebC, take note that it is possible to wire up the method below in WebC. However it is recommended to use the provided <eleventy-image> WebC component instead.

Advanced

Boost Performance: Optimize Images on Request

(vv3.0.0-alpha.7)(vImage v5.0.0)The transformOnRequest feature is available for free with the Image HTML Transform and the Image WebC component.

Configuration

You can use transformOnRequest with Eleventy Shortcodes too with a little bit more configuration:

eleventy.config.js
import Image from "@11ty/eleventy-img";
import { eleventyImageOnRequestDuringServePlugin } from "@11ty/eleventy-img";

export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
let html = await Image(src, {
transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve",
returnType: "html",
htmlOptions: {
imgAttributes: {
alt, // required
},
}
});

    	return html;
    });

    // Add the dev server middleware manually
    eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin);

};
const Image = require("@11ty/eleventy-img");
const { eleventyImageOnRequestDuringServePlugin } = require("@11ty/eleventy-img");

module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
let html = await Image(src, {
transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve",
returnType: "html",
htmlOptions: {
imgAttributes: {
alt, // required
},
}
});

    	return html;
    });

    // Add the dev server middleware manually
    eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin);

};

Using Shortcodes Alongside the Image HTML Transform Method

If you’re using an Image Shortcode or the WebC component in a project and you’re also adding the Image HTML Transform make sure you add eleventy:ignore to the <img> attributes so the images aren’t processed twice:

eleventy.config.js
import Image from "@11ty/eleventy-img";

export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
let html = await Image(src, {
returnType: "html",
htmlOptions: {
imgAttributes: {
alt, // required
"eleventy:ignore": ""
}
}
});

    	return html;
    });

};
const Image = require("@11ty/eleventy-img");

module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
let html = await Image(src, {
returnType: "html",
htmlOptions: {
imgAttributes: {
alt, // required
"eleventy:ignore": ""
}
}
});

    	return html;
    });

};

Using Image.generateHTML to create markup

eleventy.config.js
import Image from "@11ty/eleventy-img";

export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
let metadata = await Image(src, {
widths: [600],
formats: ["jpeg"],
});

    	return Image.generateHTML(metadata, {
    		alt, // required
    	});
    });

};
const Image = require("@11ty/eleventy-img");

module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
let metadata = await Image(src, {
widths: [600],
formats: ["jpeg"],
});

    	return Image.generateHTML(metadata, {
    		alt, // required
    	});
    });

};

Make your own markup

If you have an advanced use case and don’t want to use returnType: "html" or Image.generateHTML to create image markup, you can do it yourself!

Uses the entities npm package.

eleventy.config.js
import { escapeAttribute } from "entities";
import Image from "@11ty/eleventy-img";

export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
if (alt === undefined) {
// You bet we throw an error on missing alt (alt="" works okay)
throw new Error(`Missing \`alt\` on myImage from: ${src}`);
}

    	let metadata = await Image(src, {
    		widths: [600],
    		formats: ["jpeg"],
    	});

    	let data = metadata.jpeg[metadata.jpeg.length - 1];
    	return `<img src="${data.url}" width="${data.width}" height="${data.height}" alt="${escapeAttribute(alt)}" loading="lazy" decoding="async">`;
    });

};
const { escapeAttribute } = require("entities");
const Image = require("@11ty/eleventy-img");

module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
if (alt === undefined) {
// You bet we throw an error on missing alt (alt="" works okay)
throw new Error(`Missing \`alt\` on myImage from: ${src}`);
}

    	let metadata = await Image(src, {
    		widths: [600],
    		formats: ["jpeg"],
    	});

    	let data = metadata.jpeg[metadata.jpeg.length - 1];
    	return `<img src="${data.url}" width="${data.width}" height="${data.height}" alt="${escapeAttribute(alt)}" loading="lazy" decoding="async">`;
    });

};

Synchronous Shortcode

Deprecated in Eleventy Image v4.0.0.

The new Eleventy Transform is now preferred for situations that are not asynchronous-friendly (Handlebars, macros in Nunjucks, et al). For asynchronous-friendly templates (e.g. Nunjucks, Liquid, JavaScript), the Asynchronous Shortcode is another option. If you’re using WebC, use the provided WebC component.

Configuration

Use Image.statsSync to get the metadata of a source even if the image generation is not finished yet:

eleventy.config.js
import Image from "@11ty/eleventy-img";

export default function (eleventyConfig) {
eleventyConfig.addShortcode("myImage", function imageShortcode(src, cls, alt, widths = ["auto"], sizes = "100vh") {
let options = {
widths,
formats: ["jpeg"],
};

    	// generate images: this is async but we don’t wait
    	Image(src, options);

    	let imageAttributes = {
    		class: cls,
    		alt,
    		sizes,
    		loading: "lazy",
    		decoding: "async",
    	};
    	// get metadata even if the images are not fully generated yet
    	let metadata = Image.statsSync(src, options);
    	return Image.generateHTML(metadata, imageAttributes);
    });

};
const Image = require("@11ty/eleventy-img");

module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("myImage", function imageShortcode(src, cls, alt, widths = ["auto"], sizes = "100vh") {
let options = {
widths,
formats: ["jpeg"],
};

    	// generate images: this is async but we don’t wait
    	Image(src, options);

    	let imageAttributes = {
    		class: cls,
    		alt,
    		sizes,
    		loading: "lazy",
    		decoding: "async",
    	};
    	// get metadata even if the images are not fully generated yet
    	let metadata = Image.statsSync(src, options);
    	return Image.generateHTML(metadata, imageAttributes);
    });

};