-
Hey all, The hero section on my site features the most recent blog post. The background of the hero is the featured image of that post. https://www.whatifididnt.com Here's how I'm applying the background currently. In the CSS file: I am updating this manually. Is there a way that I could make it dynamic by automatically grabbing the featured image URL from the front matter of the most recent post? Thanks, -Ben |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
@benpages Two immediate options come to mind (one reasonable, one is... [almost comically] less so). In no particular order: ---
# ./src/assets/site.css.njk
permalink: assets/site.css
---
{%- set latest = collections.pages | last -%}
.home__hero {
background-image: url("{{ latest.data.hero }}");
} By moving some of your CSS into an .njk template, we can fetch the newest item from our imaginary ---
title: Five
date: 2022-03-14
hero: ../assets/blog/five-bag-travel.jpg
---
<h1>{{ title }}</h1> Eleventy will process the ./src/assets/site.css.njk file, and write the output as ./_site/assets/site.css (due to the The other option was to change your CSS above: -background-image: url("../assets/blog/one-bag-travel.jpg");
+background-image: url("../assets/blog/latest.jpg"); Then when you create a new blog post and create a new blog hero image, make a copy of the image and overwrite the previous version of ../assets/blog/latest.jpg. Requires less coding, but you still have to remember to overwrite the older "latest.jpg" asset each time you publish a new post, so probably doesn't save you much time/effort/mental space. |
Beta Was this translation helpful? Give feedback.
@benpages Two immediate options come to mind (one reasonable, one is... [almost comically] less so).
In no particular order:
By moving some of your CSS into an .njk template, we can fetch the newest item from our imaginary
collections.pages
collection and then dynamically set thebackground-image
to thehero
property from the front matter. For example, here's my ./src/pages/five.njk file:Eleventy will process the .…