
在客户端使用 LiquidJS 时,{% include %} 标签默认无法自动加载子模板,需通过配置 root 选项指定模板根路径,并确保 HTML 文件能直接访问 .liquid 模板资源,方可实现嵌套渲染。
在客户端使用 liquidjs 时,`{% include %}` 标签默认无法自动加载子模板,需通过配置 `root` 选项指定模板根路径,并确保 html 文件能直接访问 `.liquid` 模板资源,方可实现嵌套渲染。
LiquidJS 在浏览器中运行时,include 标签的行为与服务端一致——它会尝试根据模板名(如 'summary-group-block')拼接路径,从配置的 root 目录下加载对应文件(默认扩展名为 .liquid)。但若未显式配置 root 或模板文件未以可访问的静态资源形式部署,就会抛出 RenderError: Not Found。
✅ 正确做法是:初始化引擎时指定 root 和 extname,并确保所有被 include 的模板可通过 HTTP 路径访问(例如作为静态资源托管在 /views/partials/booking/ 下):
import { Liquid } from 'liquidjs';
const engine = new Liquid({
root: '/views/partials/booking/', // 模板根目录(相对于网站根路径)
extname: '.liquid', // 模板扩展名,用于自动补全
// 可选:启用缓存提升性能(生产环境推荐)
cache: true,
});随后,直接调用 renderFile() 即可触发递归加载:
// 自动加载 /views/partials/booking/summary-block.liquid
// 并在渲染过程中按需加载 /views/partials/booking/summary-group-block.liquid
engine.renderFile('summary-block', {
summary: {
summaryGroups: [
{ bookingGroupLabel: 'Standard', unitTotal: 2, subtotal: 200, discount: 10, savings: 20, total: 180 },
{ bookingGroupLabel: 'Premium', unitTotal: 1, subtotal: 150, discount: 0, savings: 0, total: 150 }
]
}
}).then(html => {
document.getElementById('container').innerHTML = html;
});⚠️ 注意事项:
-
root必须是浏览器可直接请求的相对或绝对 URL 路径(如/views/...),而非本地文件系统路径; - 所有被
include的模板(如summary-group-block.liquid)需真实存在于该路径下,且服务器需正确配置 MIME 类型(建议返回text/plain或text/html,避免跨域或 CORS 问题); - 若模板位于
<script type="text/template"></script>标签或 JS 字符串中,include不会自动识别——此时应改用registerPartial()手动注册子模板; - 开发阶段建议关闭
cache: false便于实时调试;生产环境开启cache: true可显著减少重复解析开销。
? 小技巧:如需完全脱离 HTTP 请求(例如模板已内联),可结合 registerPartial() 预注册:
engine.registerPartial('summary-group-block', `
<tr>
<td>{{group.bookingGroupLabel}}</td>
<td class="text-end">{{group.unitTotal}}</td>
<td class="text-end">{{group.subtotal | price}}</td>
<td class="text-end">{{group.discount | percentage}}</td>
<td class="text-end">{{group.savings | price}}</td>
<td class="text-end">{{group.total | price}}</td>
</tr>
`);
// 此后 {% include 'summary-group-block' %} 将直接使用注册内容综上,客户端 include 完全可行,关键在于统一模板分发机制与引擎配置对齐——既支持静态资源加载,也兼容运行时注册,灵活适配不同工程场景。


















