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

如何将LiquidJS的输出保存到变量中?

LiquidJS 渲染结果保存到变量的方法

原示例代码通过.then(console.log)直接打印渲染结果,要将结果保存到变量中,有两种常用实现方式:

方法一:在Promise回调中赋值

借助Promise的then方法接收渲染结果,将其赋值给预先声明的变量:

import { Liquid } from 'liquidjs'
const engine = new Liquid()
const tpl = engine.parse('Welcome to {{v}}!')

// 声明变量用于存储渲染结果
let renderResult;

engine.render(tpl, {v: "Liquid"}).then(res => {
  renderResult = res;
  // 此处可对renderResult执行后续逻辑
  console.log(renderResult); // 输出: Welcome to Liquid!
})

方法二:使用async/await语法

通过异步函数配合await关键字,以类同步的写法获取并保存结果,代码可读性更强:

import { Liquid } from 'liquidjs'
const engine = new Liquid()
const tpl = engine.parse('Welcome to {{v}}!')

async function getRenderedContent() {
  // 直接await获取渲染结果并赋值
  const renderResult = await engine.render(tpl, {v: "Liquid"});
  // 后续可直接使用renderResult
  console.log(renderResult); // 输出: Welcome to Liquid!
}

// 调用异步函数触发渲染
getRenderedContent();

需要注意:engine.render是异步操作,必须在异步上下文(then回调或async函数)中才能正确获取和使用结果,同步代码中无法直接访问未完成赋值的变量。

内容的提问来源于stack exchange,提问作者Sandra Schlichting

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:06:24