我认为 Markdown 中没有类似的备用图像规范,但如果您使用 markdown-it(这是 Eleventy 中的默认降价解析器),您可以添加自定义插件来扩展语法。您也可以只将 HTML 放入您的 markdown,或者如果您使用 Eleventy,您甚至可以在您的 markdown 中使用简码。
使用简码
您可以在 Eleventy 中定义 custom shortcodes,然后再定义 use them in your markdown。这可能比设置markdown-it 插件更容易、更灵活,但缺点是将非降价的东西放在你的降价中。
使用markdown-it 插件
如果您已经有要使用的预生成图像,您可能需要使用markdown-it-picture 之类的东西并修改它以设置type 属性,方法是解析文件扩展名或更改媒体查询/标题点改为接受type。您需要将代码复制到项目中的新文件中,进行修改,然后像这样注册它:
// .eleventy.js
module.exports = function(eleventyConfig) {
const mdPicture = require('/path/to/plugin.js')
const md = require('markdown-it')()
md.use(mdPicture)
eleventyConfig.setLibrary('md', md)
// ...
};
与eleventy-image
或者,如果您还没有生成图像并希望在 11ty 构建步骤中生成它们,您可以使用eleventy-image (Docs)。这个Twitter thread 讨论了创建自定义markdown-it 渲染器,我已经修改它以与下面的eleventy-image 一起使用。
// you might want to put this in another file
// such as ./utils/markdown.js
// responsive images with 11ty image
// this overrides the default image renderer
// titles are also used for size setting (optional)
//
//  100vw, 768px')
const md = require('markdown-it')();
const Image = require('@11ty/eleventy-img')
md.renderer.rules.image = function (tokens, idx, options, env, self) {
const token = tokens[idx]
let imgSrc = token.attrGet('src')
const imgAlt = token.content
// you can modify the default sizes, or omit
const imgSize = token.attrGet('title') || '(max-width: 768px) 100vw, 768px'
const widths = [250, 426, 580, 768] // choose your own widths, or [null] to disable resize
const imgOpts = {
widths: widths
.concat(widths.map((w) => w * 2)) // generate 2x sizes for retina displays
.filter((v, i, s) => s.indexOf(v) === i), // dedupe widths
formats: ['webp', 'jpeg'], // choose your own formats (see docs)
urlPath: '/assets/img/', // src path in HTML output
outputDir: './_site/assets/img/' // where the generated images will go
}
// generate the images
// see https://www.11ty.dev/docs/plugins/image/#synchronous-usage
Image(imgSrc, imgOpts)
const metadata = Image.statsSync(imgSrc, imgOpts)
return Image.generateHTML(metadata, {
alt: imgAlt,
sizes: imgSize,
loading: 'lazy',
decoding: 'async'
})
}
// in your .eleventy.js
module.exports = function(eleventyConfig) {
// you may need to `require` the file with
// your markdown config with the custom renderer
// const md = require('./utils/markdown.js')
eleventyConfig.setLibrary('md', md)
// ...
};
这个渲染器会自动为你生成不同尺寸的图片,以及不同的格式,然后在你的HTML中输出<picture>标签。由于 markdown-it 不能很好地配合async 函数,我们使用eleventy-image 的syncronous pattern。更多配置信息请见docs。
您可能需要注意的一件事是,markdown 中的图像路径应该是图像在您的网站源中的位置,不是最终发布的 URL。例如,我的图像可能位于src/images/img.png,但发布在https://example.com/images/img.png。降价应该是 和NOT 。您还可以在渲染器函数中进行额外的解析。