如何使用Liquid列出目录中的文件?

Ces*_*sco 27 liquid jekyll

我正在努力学习如何使用Jekyll和Bootstrap; 在研究它们时,我决定在我的主页上有一个图像轮播.

因为我真的很懒,所以我不想硬编码显示布局中每个图像所需的路径,我也不想使用数组来存储图像列表.

我想知道是否有任何标签可以让Jekyll做这两个步骤:

  1. 查看特定目录
  2. 对于您在该目录中找到的每个文件,重复一段代码

基本上我想写的东西模糊地类似于这段(想象的)代码:

{% for file in directory %}
    <img src="{{ file.url }}" />
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

因此,例如,如果我有一个包含三个文件的文件夹,名为image01.jpg,image02.jpg,image03.jpg,我想jekyll可以为我构建这个HTML代码:

<img src="folder/image01.jpg" />
<img src="folder/image02.jpg" />
<img src="folder/image03.jpg" />
Run Code Online (Sandbox Code Playgroud)

所以我看了一下这个参考页面,但是我找不到任何有用的东西.

拜托,您能否给我任何建议,如果可能的话,还有一个不涉及使用插件的建议?

先感谢您.

jga*_*ens 18

你可以使用这个插件.将此代码复制并粘贴到_pluginsJekyll项目根目录下的文件中.

https://gist.github.com/jgatjens/8925165

然后使用它只需添加下面的行

{% loop_directory directory:images iterator:image filter:*.jpg sort:descending %}
   <img src="{{ image }}" />
{% endloop_directory %}
Run Code Online (Sandbox Code Playgroud)

  • 虽然它涉及添加插件,但这应该是正确的答案,因为它几乎正是 OP 想要做的 (2认同)

aga*_*rie 14

没有插件,这并非完全不可能,但当然你需要使用一些kludges.例如,您可以将图像路径放在YAML前端,当Jekyll处理您的页面时它们将可用.

---
carousel_images:
  - images/img01.png
  - images/img02.png
  - images/img03.png
---

# Lots of page-related code.

{% for img in page.carousel_images %}
  # Do something.
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

对于网站范围的图片,您需要一个插件.但是,如果您希望图像位于特定页面或帖子中,则应该这样做.:)

希望有所帮助!


rap*_*ael 14

Using the Jekyll collections API, which, as of 2015-08-07 came with the big warning

Collections support is unstable and may change

Define a collection in _config.yml and creates an _images folder in your root directory

collections:
- images
Run Code Online (Sandbox Code Playgroud)

Without having to add YAML front-matter to your images, Jekyll will:

集合中没有前端内容的文件被视为静态文件,只是简单地复制到其输出位置而不进行处理.

静态文件具有以下属性:

  • file.path
  • file.extname

然后页面上的代码就像(未经测试):

{% for image in site.images %}
     {% if image.extname == 'jpg' %}
         <img src="{{ file.url }}" />
     {% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


Gab*_*yas 8

根据@raphael的答案,您可以使用以下代码列出jpg文件:

{% for file in site.static_files %}
  {% if file.extname == ".jpg" %}
     * [{{ file.path }}]({{ site.baseurl }}{{ file.path }})
  {% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

您可能希望删除一些换行符,以在输出中获得一个列表(而不是仅包含一个元素的列表)。


Pol*_*ome 6

编辑(2015-11-09): 杰基尔后来得到了一些更新,特别是site.static_pages.检查@raphael答案以获得可能的解决方案.

没有使用插件是不可能的.您在Liquid Templates中没有I/O功能.

如果您的图像有前端问题,它们可能会被Jekyll处理并存储在site.pages数组中,因此可以访问,但我不建议将Front Matter放在图像上(可能对SVG有意义,但对其他任何内容都没有意义) ).

你最好的选择可能是写一个小的shell脚本来扫描你的文件夹中的图像并创建一个images.json文件.然后可以通过Ajax加载此文件.您每次上传新文件时都必须重新创建images.json文件(如果您使用的是Git,则可以将其作为预提交钩子).