Jekyll - 使用 {{ site.url }} 将前面的图像路径声明为变量 [英] Jekyll - declare image path in front matter as variable using {{ site.url }}

查看:10
本文介绍了Jekyll - 使用 {{ site.url }} 将前面的图像路径声明为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将 {{ site.url }} 标签用于前面的变量中的图像路径时,它不会被翻译成 HTML.

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.

以下工作完美:

---
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)]">
---

这不起作用:

---
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)]">
---

但是当我在帖子中使用带有 {{site.url}} 标签而不是作为变量的相同图像链接时,它可以工作.

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

分析生成的站点显示,当我在前面定义的图像变量中使用 {{site.url}} 标记时,Jekyll 没有转换它.

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.

所以问题是:如何让 Jekyll 正确翻译 YAML 前端的图像路径?

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

推荐答案

你在 yaml 中混合数据和模板.您的图像标签(这是一个模板)将在您的所有帖子中重复.但是您在这里唯一需要的是您的图片网址.

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.

所以,在你的 yaml 前面,做:

So, in your yaml front matter, do :

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

您可以在 layout/post.html 中添加:

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 %}

这段代码是多行的,用于演示目的.你最好把所有东西放在一条线上.

注意:我使用的是 {{site.baseurl}} 而不是 {{site.url}} 因为如果您的网站不在域的根目录 baseurl 将使您免于损坏的资产路径.

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.

现在您有了清晰的关注点分离、清晰的 yaml 前端内容和可维护的代码.是不是很酷?

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

这篇关于Jekyll - 使用 {{ site.url }} 将前面的图像路径声明为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆