Skip to content

A new way to extract images from blog posts and show them in the postlist? #188

Open
@verlok

Description

@verlok

Hey,

I am running my blog post in Eleventy v2 and currently migrating to v3.
All good, except 1 thing.

My workaround to extract images from blog posts and show them in the postlist doesn't work anymore.
Here's what I was doing in v2. The key is that extractImage.

Adding a filter called extractImage in the eleventy config file, which relied on JSDOM:

const correctLazyAttributes = (img, isFirst) => {
	if (isFirst) {
		img.setAttribute("fetchpriority", "high");
		img.setAttribute("loading", "eager");
	} else {
		img.removeAttribute("fetchpriority");
		img.setAttribute("loading", "lazy");
	}
};

eleventyConfig.addFilter("extractImage", function (content, isFirst) {
	const dom = new JSDOM(content);
	const img = dom.window.document.querySelector("img");
	if (!img) return "";
	img.classList.add("postlist-image");
	correctLazyAttributes(img, isFirst);
	const picture = img.closest("picture");
	//const returnedTag = picture || img;
	return (picture || img).outerHTML;
});

Then in the postlists.njk I was doing:

{% set firstImage = true %}
<section class="postlist">
{% for post in postslist | reverse %}
	{% set imageHTML = post.templateContent | extractImage(firstImage) %}	
	{% set articleModifier = 'postlist-item--no-image' if imageHTML=='' else 'postlist-item--with-image' %}
	<article class="postlist-item {{ articleModifier }}">
		<a href="{{ post.url }}" class="postlist-link">
			<h1 class="postlist-title">
				{% if post.data.title %}{{ post.data.title }}
				{% else %}
					<code>{{ post.url }}</code>
				{% endif %}
			</h1>
			{{ post.templateContent | extractImage(firstImage) | safe }}
			{% set firstImage = false %}
			{% if post.data.description %}
				<p class="postlist-description">{{ post.data.description }}</p>
			{% endif %}
			<div class="postlist-buttonslot">
				<span class="postlist-button">Read more &rarr;</span>
			</div>
		</a>
		{# <time class="postlist-date" datetime="{{ post.date | htmlDateString }}">{{ post.date | readableDate("LLLL yyyy") }}</time>#}
	</article>
{% endfor %}
</section>

The reason why this doesn't work anymore in v3 is that I'm now trying to use the new eleventyImageTransformPlugin, and that sees the generated images in the home page and tries to process them again, this time not finding the source file.

Any hint on how to make this work, or even to improve this tricky hack?

Thanks

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      A new way to extract images from blog posts and show them in the postlist? · Issue #188 · 11ty/eleventy-base-blog