Template macros/functions possible?

I often find myself having to add certain types of content that requires HTML/CSS that is not possible to do in pure Markdown.

For example, I might want to add an image to a blog post like this:

<div class="text-center">
<img class="article-image" src="/assets/images/diagram.png">
<p class="text-muted text-center">Image:
By Joe Smith (CC BY-SA 3.0)
</p>
</div>

Of course, Jekyll allows me to just put this HTML into my markdown blog post. So that is all great and works.
However, the problems start when I want to, say add a CSS class to the img tag. Then I have to go through all blog posts that have images in them and add the class to all instances.

Also having to add this code everywhere is error prone: I may forget to add some class in one post. Or I may make a typo in another post, etc.
This causes things to get messy really fast.

So I was thinking if it is possible to create a small library of template macros or functions that I would be able to call.

Something like:

{% blog_image(imgsrc="diagram.png", credit="Joe smith (CC BY-SA 3.0)") %}

Which would then generate:

<div class="text-center">
<img class="article-image" src="{{ imgsrc }}">
<p class="text-muted text-center">Image:
By {{ credit }}
</p>
</div>

Is this possible?

1 Like

Yes, you can use a Liquid include tag with parameters. See these docs on how includes works in Jekyll. Example:

{% include blog_image.html imgsrc="diagram.png" credit="Joe smith" %}
1 Like

This seems to work.

Is this a common pattern that people use in this way?
Or is there a better way to do stuff like this?

while the include syntax looks a bit wordy, it works very well for me. Whenever I repeat myself in code, I check whether it makes sense to generalise the stuff a bit and make it into an include. The default values for arguments are very handy there.
As example, to make an include very general, I use the file_exists plugin, for instance to include images w/o specifying whether they are .png or .jpg or .webp.