shopify - 如何使用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 匹配,如果这允许任何可能性。
解决方案
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 %}
推荐阅读
- node.js - 无效的 socks 版本 SOCKS 模块 NODEJS
- amazon-web-services - 无法通过 SSH 连接
- css - 在 Kotlin CSS 中的 CSS @
- r - 每次读取新的 .csv 文件时将数据添加到数据框中
- vb.net - 如何启用和禁用外键约束
- java - java GUI设置cardlayout帧大小
- android - Android ProgressBar setProgress() 无法按预期工作
- javascript - 发送 post 请求 XMLHttprequest
- css - 为什么动画元素宽度会导致同一行中的其他元素有点抖动?
- python - Selenium 使用 vscode 进行行为调试 - python