How to create custom HTML output for an existing Asciidoctor Asciidoc macro?
Asked Answered
A

1

2

For example, I want to add the loading="lazy" attribute to all my images e.g.:

image::myimage.jpg[]

but the default HTML <img> element output does not have that attribute.

Maybe this is was asked at: Creating custom HTML with asciidoctor but the question is not clear enough for me to be sure about it.

Avelar answered 16/9, 2020 at 10:22 Comment(0)
A
2

This is documented at: https://asciidoctor.org/docs/user-manual/#provide-custom-templates but it feels like a minimal example would be beneficial.

main.adoc

image::myimage.jpg[]

template_dir/block_image.html.erb

<%#encoding:UTF-8%><div<%= @id && %( id="#{@id}") %> class="<%= ['imageblock',@style,role].compact * ' ' %>"<%
if (attr? :align) || (attr? :float)
%> style="<%= [("text-align: #{attr :align};" if attr? :align),("float: #{attr :float};" if attr? :float)].compact * ' ' %>"<%
end %>>
<div class="content"><%
if attr? :link %>
<a class="image" href="<%= attr :link %>"><img src="<%= image_uri(attr :target) %>" loading="lazy" alt="<%= attr :alt %>"<%= (attr? :width) ? %( width="#{attr :width}") : nil %><%= (attr? :height) ? %( height="#{attr :height}") : nil %>></a><%
else %>
<img src="<%= image_uri(attr :target) %>" loading="lazy" alt="<%= attr :alt %>"<%= (attr? :width) ? %( width="#{attr :width}") : nil %><%= (attr? :height) ? %( height="#{attr :height}") : nil %>><%
end %>
</div><%
if title? %>
<div class="title"><%= captioned_title %></div><%
end %>
</div>

This is a copy the default template from https://github.com/asciidoctor/asciidoctor-backends/blob/master/erb/html5/block_image.html.erb, but with the HTML modified by adding loading="lazy".

Gemfile

gem 'asciidoctor', '2.0.10'
gem 'concurrent-ruby', '1.1.7'
gem 'tilt', '2.0.10'

We need to install those extra gems for it to work.

Compile:

asciidoctor --template-dir template_dir main.adoc

and that's it, the output HTML now contains loading="lazy".

Tested in Asciidoctor 2.0.10.

Avelar answered 16/9, 2020 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.