首页 > 解决方案 > 如何使用带有 srcset 属性的图片元素从 Asciidoc 源输出具有响应式图像的 HTML5?

问题描述

所以,如果我想要看起来像这样的 HTML5 输出:

<picture>
  <source type="image/svg+xml" srcset="pyramid.svg">
  <source type="image/webp" srcset="pyramid.webp">
  <img src="pyramid.png" alt="regular pyramid built from four equilateral triangles">
</picture>

(取自这里

我的 AsciiDoc 源代码会是什么样子?也许是一个带有多个图像的图形,它使用自定义后端转换为这个图形,还是什么?这甚至可以使用 AsciiDoc/Asciidoctor 来实现吗?

标签: htmlsrcsetasciidocasciidoctor

解决方案


这绝对是可能的!
使用内置image宏,您可以定义如下内容:

image::pyramid.png[regular pyramid built from four equilateral triangles,sources="pyramid.svg,pyramid.webp"]

请注意,该sources属性将在Image块上可用。

然后,使用自定义转换器,您可以检索此属性的值以构建<source>元素(包装在<picture>元素中)。
这是一个简化的示例:

MIME_TYPES = {
  ".svg" => 'image/svg+xml',
  ".webp" => 'image/webp'
}

def convert_image node
  target = node.attr 'target'
  sources = (node.attr 'sources', '').split(',').map do |src|
    %(<source type="#{MIME_TYPES[File.extname src]}" srcset="#{src}">)
  end
  %(<picture>
#{sources.join("\n")}
<img src="#{target}" alt="#{node.alt}">
</picture>)
end

您当然可以使用附加属性来做更高级的事情。

请记住,也可以使用扩展来扩展 AsciiDoc 语法。话虽如此,在这种情况下,我认为最好使用内置image宏来保留语义信息。


推荐阅读