如何在Liquid的for循环中创建数组?

24

我正在尝试使用Liquid语法从对象列表创建数组:

{% for operation in menuItems %}
      {% assign words1 = operation.Title | split: '_' %}
      {% assign controllerName = words1 | first %}
      {% assign controllersTmp = controllersTmp | append: '_' | append: controllerName %}
{% endfor %}

我想把controllersTmp分割以获得我的数组,但此时我的controllersTmp为空。

有什么帮助吗?

3个回答

38

您可以直接创建一个新的空数组controllers,并使用concat将您的controllerName转换为一个数组,使用split:''方法来实现。结果会直接是一个数组,不需要进行额外的字符串操作。

{% assign controllers = '' | split: '' %}
{% for operation in menuItems %}
    {% assign controllerName = operation.Title | split: '_' | first | split: '' %}
    {% assign controllers = controllers | concat: controllerName %}
{% endfor %}

Maroine,这个在API管理模板中按要求工作了吗?我尝试做类似的事情,但好像不能使用concat - Nicolas R
1
如果controllerName本身不是一个数组(我认为在OP的问题中它不会是),则您需要在最后一个赋值中使用append。并且您可以跳过第一个赋值中的split。 - relizt

6

我的经验

{% assign otherarticles = "" | split: ',' %}
{% assign software_engineering = "" | split: ',' %}

{% for file in site.static_files %}
  {% if file.extname == ".html" %}
    {% if file.path contains "software_engineering" %}
       {% assign software_engineering = software_engineering | push: file %}
    {% else %}
      {% assign otherarticles = otherarticles | push: file %}
    {% endif %}
  {% endif %}
{% endfor %}


推送过滤器的定义是什么?我收到了“未定义的过滤器推送”。 - Tom Smykowski
我相信push是Jekyll添加的一个过滤器:https://jekyllrb.com/docs/liquid/filters/ - Fluffy

-3

你需要初始化变量 controllersTmp:

 {% assign controllersTmp = '' %}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接