Jim
Jim

Reputation: 239

Asciidoctor images that are links to the image

The following Asciidoc code creates an image (with suitable styling etc) such that if you click on it, you open the image:

image:./myimage.jpg[my alt text, role="my css styling", link="./myimage.jpg"]

Note the path to the jpg file ./myimage.jpg is duplicated. This is inelegant, invites typos, and if the path is long it can become quite inconvenient to maintain.

My question is this: is there a neat way to achieve this effect that does not require duplicating the path to the image, so that the path to the image is included precisely once in the code?

Thank you.

Upvotes: 5

Views: 1044

Answers (2)

9769953
9769953

Reputation: 12221

This is possible by defining an attribute:

:myimage: ./myimage.png
image::{myimage}[my alt text, role="my css styling", link="{myimage}"]

(also note: :: instead of a single :).

This becomes something like the following when run through AsciiDoctor:

<div class="content">
<a class="image" href="./myimage.png"><img src="./myimage.png" alt="my alt text"></a>
</div>

This is obviously more text, but as you mentioned, maintenance (certainly for long file names or URLs to external images) becomes easier.

Be aware that the space between :myimage: and ./myimage.png is required.

Also, if you redefine the attribute later in the document, it will only impact the next uses of the attribute. Thus,

:myimage: ./myimage.png
image::{myimage}[my alt text, role="my css styling", link="{myimage}"]

:myimage: ./myimage2.png
image::{myimage}[my second alt text, role="my css styling", link="{myimage}"]

will render two different images: the second attribute definition doesn't override the first one.
Though one may prefer different attribute names in such cases.

Upvotes: 2

Jim
Jim

Reputation: 239

I couldn't see how to do this in pure Asciidoc and would still welcome input on the matter. In the meantime, I worked around the problem.

I'm in Jekyll so I used a Liquid template. I placed a file myimage in the _includes directory

image:{{ include.p }}[{{ include.t }}, link="{{ include.p }}"]

and invoked it with

{% include myimage p="image-name.jpg" t="alt text" %}

This is actually a slight simplification. In full, myimage is

[.cssstyling]#image:{{ include.p }}[{{ include.t }}, link="{{ include.p }}"]{% if include.c != null %}_{{include.c}}_{% endif %}#

and the invocation is one of the following:

{% include myimage p="image-name.jpg" t="alt text" %}
{% include myimage p="image-name.jpg" t="alt text" c="optional caption" %}

Upvotes: 0

Related Questions