Duncan Lock
Duncan Lock

Reputation: 12751

How can I output HTML5, that has responsive images, using picture elements with srcset attributes, from Asciidoc source?

So, if I wanted HTML5 output that looked like this:

<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>

(taken from here)

What would my AsciiDoc source look like? Maybe a figure, with multiple images, which is transformed to this using a custom backend, or something? Is this even possible to do using AsciiDoc/Asciidoctor?

Upvotes: 0

Views: 205

Answers (1)

Mogztter
Mogztter

Reputation: 491

It's definitely possible!
Using the built-in image macro, you could define something like:

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

Please note that the sources attribute will be available on the Image block.

Then, using a custom converter, you could retrieve the value of this attribute to build <source> elements (wrapped in a <picture> element).
Here's a simplified example:

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

You can certainly do more advanced stuff using additional attributes.

Keep in mind that it's also possible to extend the AsciiDoc syntax using extensions. Having said that, in this case, I think it's better to use the built-in image macro to preserve semantic information.

Upvotes: 3

Related Questions