首页 > 解决方案 > 如何为现有的 Asciidoctor Asciidoc 宏创建自定义 HTML 输出?

问题描述

例如,我想将loading="lazy"属性添加到我的所有图像中,例如:

image::myimage.jpg[]

但默认的 HTML<img>元素输出没有该属性。

也许有人问过这个问题:使用 asciidoctor 创建自定义 HTML,但问题不够清楚,我无法确定。

标签: asciidocasciidoctor

解决方案


这记录在:https ://asciidoctor.org/docs/user-manual/#provide-custom-templates但感觉像一个最小的例子会是有益的。

主文件

image::myimage.jpg[]

模板目录/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>

这是来自https://github.com/asciidoctor/asciidoctor-backends/blob/master/erb/html5/block_image.html.erb的默认模板的副本,但 HTML 通过添加loading="lazy".

宝石文件

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

我们需要安装这些额外的 gem 才能让它工作。

编译:

asciidoctor --template-dir template_dir main.adoc

就是这样,输出 HTML 现在包含loading="lazy".

在 Asciidoctor 2.0.10 中测试。


推荐阅读