Jekyll - declare image path in front matter as variable using {{ site.url }}

房东的猫 提交于 2019-12-21 04:23:05

问题


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. :)



来源:https://stackoverflow.com/questions/25295418/jekyll-declare-image-path-in-front-matter-as-variable-using-site-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!