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

查看:569
本文介绍了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)]">
---

但当我使用与<$ c $相同的图片链接时c> {{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.

分析生成的网站显示,当我在前面的事物中定义的图像变量中使用它时,Jekyll不会转换 {{site.url}} 标记。

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

在你的布局/ 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天全站免登陆