Gelernt - GitHub Copilot, Nunjucks und 11ty inputPath
Problem
Hier wird der letzte Post auf der Startseite gerendert. Das führt dazu, dass 11ty das Bild unter ./src/ sucht, wo es aber nicht liegt. In diesem Fall stimmen vom gerenderten Output die Pfade in <img src="..."/> nicht. Der src-Pfad muss durch den korrekten inputPath des original-Posts ersetzt werden.
Prompt
create the nunjuck for when mostRecent.data.page.inputPath ends with "/index.md" replace all img src with the path
Answer
To conditionally replace all <img src= with the correct path when mostRecent.data.page.inputPath ends with /index.md, use a Nunjucks if statement and the replace filter. Here’s how you can do it:
{% set inputPath = mostRecent.data.page.inputPath %}
{% if inputPath.endsWith('/index.md') %}
{{ mostRecent.content | replace('<img src=', '<img src=' ~ inputPath | replace('/index.md', '/') ) | safe }}
{% else %}
{{ mostRecent.content | safe }}
{% endif %}This checks if the input path ends with /index.md and prepends the directory path to all image sources.
Final resolution
Nach ein paar Anpassungen verwende ich diese Lösung:
{% set inputPath = mostRecentPost.data.page.inputPath %}
{% if inputPath.startsWith("./src") and inputPath.endsWith('/index.md') %}
{% set inputPath = inputPath | replace('./src', './') %}
{% set inputPath = inputPath | replace('/index.md', '/') %}
{% set content = content | replace('<img src="', '<img src="' ~ inputPath) %}
{% endif %}