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

如何使用Handlebars展示LocalStorage中存储的数据?

使用Handlebars展示LocalStorage中的数据

看起来你已经完成了数据存储到LocalStorage的步骤,接下来只需要补上Handlebars模板编译和渲染的环节就行,我帮你把完整流程梳理清楚:

第一步:补全JavaScript代码

你现有的代码已经拿到了模板源码,接下来需要解析LocalStorage的JSON数据、编译模板并渲染:

console.log(response); // 从控制台获取数据
var offer = JSON.stringify(response);
localStorage.setItem("object", offer); // 保存到localStorage

// 从localStorage获取数据并解析为JavaScript对象(关键!存的是字符串要转成对象)
var seasonsStr = localStorage.getItem("object");
var seasonsData = JSON.parse(seasonsStr);

// 获取Handlebars模板源码
var mysource = document.getElementById("detailstemplate").innerHTML;
// 编译模板
var template = Handlebars.compile(mysource);
// 传入数据生成HTML
var renderedHtml = template(seasonsData);
// 将渲染后的HTML插入到页面指定容器
document.getElementById("render-target").innerHTML = renderedHtml;

第二步:编写Handlebars模板

确保你的HTML里有正确的模板结构,模板要和response的字段对应,比如假设你的response是一个包含title、price、description的对象,模板可以这么写:

<!-- Handlebars模板,注意type要设为text/x-handlebars-template -->
<script id="detailstemplate" type="text/x-handlebars-template">
  <div class="offer-card">
    <h3>{{title}}</h3>
    <div class="price">¥{{price}}</div>
    <p class="desc">{{description}}</p>
    <!-- 如果是数组数据,可以用{{#each}}循环渲染 -->
    {{#each items}}
      <span class="item">{{this}}</span>
    {{/each}}
  </div>
</script>

<!-- 用来展示渲染结果的容器 -->
<div id="render-target"></div>

注意事项

  • 记得在页面中引入Handlebars库,比如本地项目可以下载后引入,或者用CDN:<script src="https://cdn.jsdelivr.net/npm/handlebars@4.7.7/dist/handlebars.min.js"></script>
  • 解析JSON的时候可以加个错误捕获,避免LocalStorage数据异常导致报错:
try {
  var seasonsData = JSON.parse(seasonsStr);
} catch (e) {
  console.error("解析LocalStorage数据失败:", e);
  seasonsData = {}; // 给个默认空对象避免模板渲染出错
}

这样就能完整实现从LocalStorage取数据,用Handlebars渲染到页面的功能啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:15:03