You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shopify Liquid中实现类似Ruby的字符串插值?

在Shopify Liquid中实现字符串插值的方法

嘿,完全可以在Shopify Liquid里实现类似Ruby的字符串插值效果!我来给你讲几种实用的方法:

方法1:Ruby风格的直接插值(推荐)

Shopify的Liquid其实支持和Ruby几乎一样的#{}插值语法,只要用双引号包裹字符串就行,直接写你想要的格式:

{% assign title_content = "the name of the teacher is #{teacher.name}" %}
{% include "layout/page_title", title: title_content %}

这样渲染后就会输出the name of the teacher is bla bla,和你想要的Ruby写法效果一致。这个方法简洁直观,适合大多数简单场景。

方法2:使用append过滤器拼接字符串

如果你的Liquid版本比较旧(不过现在Shopify基本都支持上面的插值了),可以用append过滤器来拼接字符串,这是Liquid传统的字符串处理方式:

{% assign title_content = "the name of the teacher is " | append: teacher.name %}
{% include "layout/page_title", title: title_content %}

append会把后面的变量内容直接拼接到前面的字符串末尾,效果和插值一样,兼容性拉满。

方法3:用capture标签捕获复杂内容

如果你的标题内容比较长,或者需要嵌入多个变量、HTML元素,capture标签会更合适——它能把包裹范围内的所有渲染内容(包括变量、标签输出)捕获到一个变量里:

{% capture title_content %}
the name of the teacher is {{ teacher.name }}, who teaches {{ teacher.subject }}
{% endcapture %}
{% include "layout/page_title", title: title_content %}

这种方式可读性更强,处理复杂字符串的时候不容易出错。

选哪种方法看你的场景需求就行,三种都能实现你想要的字符串插值效果~

内容的提问来源于stack exchange,提问作者Hakeem Baba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:02:56