Skip to content

Dynamic featured image? Eleventy + Njk #2351

Answered by pdehaan
benpages asked this question in Q&A
Discussion options

You must be logged in to vote

@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 collections.pages collection and then dynamically set the background-image to the hero property from the front matter. For example, here's my ./src/pages/five.njk file:

---
title: Five
date: 2022-03-14
hero: ../assets/blog/five-bag-travel.jpg
---

<h1>{{ title }}</h1>

Eleventy will process the .…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@pdehaan
Comment options

@benpages
Comment options

@pdehaan
Comment options

@benpages
Comment options

Answer selected by benpages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants