Jekyll - declare image path in front matter as var

2019-03-27 08:50发布

问题:

When I use the {{ site.url }} tag for an image path inside a variable in the front matter, it doesn't get translated into HTML.

The following works perfectly:

---
layout: post
title: chickpea
img: <img class="caption__media" data-interchange="[../asset/img/chickpea-small.jpg (small)], [../asset/img/chickpea-medium.jpg, (medium)], [../asset/img/chickpea-large.jpg, (large)]">
---

This does NOT work:

---
layout: post
title: chickpea
img: <img class="caption__media" data-interchange="[{{site.url}}/asset/img/chickpea-small.jpg (small)], [{{site.url}}/asset/img/chickpea-medium.jpg, (medium)], [{{site.url}}/asset/img/chickpea-large.jpg, (large)]">
---

But when I use the same image link with the {{site.url}} tag inside a post and not as a variable, it works.

Analysing the generated site shows that Jekyll doesn't convert the {{site.url}} tag when I use it in the image variable defined in the front matter.

So the question is: How can I get Jekyll to translate the image path in the YAML front matter correctly?

回答1:

You're mixing data and template in the yaml. Your image tag (which is a template) will be duplicated in all your posts. But the only thing you need here are your image urls.

So, in your yaml front matter, do :

---
layout: post
title: chickpea
img:
  small:  chickpea-small.jpg
  medium: chickpea-medium.jpg
  large:  chickpea-large.jpg
---

And in your layout/post.html you can add :

{% if page.img %}
  <img class="caption__media" data-interchange="
  {% for img in page.img %}
    [{{site.baseurl}}/asset/img/{{img[1]}} ({{img[0]}})]
    {% unless forloop.last %}, {% endunless %}
  {% endfor %}
  ">
{% endif %}

this code is multi-lines for demo purpose. You'd better put all on one line.

Note: I'm using {{site.baseurl}} instead of {{site.url}} because if your site is not at the root of a domain baseurl will save you from broken assets paths.

And now you have a clean separation of concerns, clear yaml front matter and maintainable code. Cool isn't it ?



回答2:

I just solved the problem using this technique: Include jekyll / liquid template data in a YAML variable?

therefore i changed the use of the variable inside the post from:

{{ post.img }}

to:

{{ post.img | replace: '..', site.url }}

I hope this helps someone with the same problem. :)