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

DotLiquid无法解析Liquid模板中的对象数组问题求助

解决DotLiquid解析Liquid模板失败的问题

问题原因

DotLiquid的语法与Shopify标准Liquid不完全兼容,它不支持在模板中直接使用[{"name": "Apple", "price": 1.99}]这种嵌套对象的数组字面量定义方式,这是导致解析失败的核心原因。

解决方案一:修正模板语法

按照DotLiquid的语法规范,先单独定义每个哈希对象,再组合成数组,同时优化循环避免末尾多余逗号:

{% assign apple = { 'name': 'Apple', 'price': 1.99 } %}
{% assign banana = { 'name': 'Banana', 'price': 0.99 } %}
{% assign orange = { 'name': 'Orange', 'price': 1.49 } %}
{% assign fruits = apple, banana, orange %}
[
{% for fruit in fruits %}
  "{{ fruit.name }} - ${{ fruit.price }}"{% unless forloop.last %},{% endunless %}
{% endfor %}
]

解决方案二:在C#代码中传入数据(推荐)

更简洁可靠的方式是在C#逻辑中构造数据集合,传入模板上下文,避免在模板中复杂的变量定义:

C#代码

using DotLiquid;
using System.Collections.Generic;
using System.IO;

// 构造数据集合
var fruits = new List<Dictionary<string, object>>
{
    new Dictionary<string, object> { { "name", "Apple" }, { "price", 1.99 } },
    new Dictionary<string, object> { { "name", "Banana" }, { "price", 0.99 } },
    new Dictionary<string, object> { { "name", "Orange" }, { "price", 1.49 } }
};

// 解析并渲染模板
var templateContent = File.ReadAllText("Test.liquid");
var template = Template.Parse(templateContent);
var renderResult = template.Render(Hash.FromDictionary(new Dictionary<string, object> { { "fruits", fruits } }));

简化后的Test.liquid模板

[
{% for fruit in fruits %}
  "{{ fruit.name }} - ${{ fruit.price }}"{% unless forloop.last %},{% endunless %}
{% endfor %}
]

内容的提问来源于stack exchange,提问作者Furqan Misarwala

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:32:43