首页 > 解决方案 > 如何使用for_loop将字符串分配给变量?

问题描述

我有一个侧边栏 ul/li,其中填充了 {% for %} 循环。当 for 循环运行时,我使用 {% cycle %} 为每个 li 分配一个特定的类,该类将为其提供 5 种背景颜色中的 1 种。这很好用。

但是,我想将此类分配扩展到侧边栏中的 li 之外,并扩展到相应产品页面上存在的对象上。我假设这将涉及分配某种类型的变量,我可以在页面的其他地方调用这些变量。

这是一个例子:

汽车 摩托车 卡车 飞机 火车

假设选择了摩托车。那个特定的侧边栏 li 被分配了一个“红色”类,并以红色显示在侧边栏中。

我想将同一个“红色”类动态加载到摩托车页面内容中的不同元素中。

我尝试在 for 循环中添加一个变量,但看不到如何在其他地方解释这个变量。


在侧边栏片段中:

{% for sidebar in sidebar_link %}
    {% assign colorvariable = "{% cycle 'purple', 'red', 'blue', 'yellow', 'green' %}" %}
    <a href="{{ sidebar.url }}"><li class="{% cycle 'purple', 'red', 'blue', 'yellow', 'green' %}">{{ sidebar.title }}</li></a>
{% endfor %}

(此代码在我添加 {% assign %} 之前有效。)

有什么正确的方法可以做到这一点吗?注意:这是一个 Shopify 网站,其中 sidebar.titles 与 page.titles 匹配,如果这允许任何可能性。

标签: shopifyliquid

解决方案


cycle是不能在标签中使用的输出assign标签。但是你可以使用capture然后使用你的变量:

{% for sidebar in sidebar_link %}
  {% capture colorvariable %}{% cycle 'purple', 'red', 'blue', 'yellow', 'green' %}{% endcapture %}
  <a href="{{ sidebar.url }}"><li class="colorvariable">{{ sidebar.title }}</li></a>
{% endfor %}

推荐阅读