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

如何在浏览器中无需require、babel等工具直接使用Handlebars.js?

直接使用Handlebars原生浏览器版本

Handlebars官方提供了可直接在浏览器运行的预构建单文件版本,完全不需要npm、babel、requirejs等构建工具和依赖,仅通过原生JS即可调用:

  • 下载官方预构建的Handlebars单JS文件到本地,直接通过script标签引入到HTML页面中即可全局使用Handlebars对象
  • 编写模板,通过type="text/x-handlebars-template"的script标签包裹模板内容,指定ID方便获取:
<!-- 模板定义 -->
<script id="demo-template" type="text/x-handlebars-template">
  <div class="item">
    <h2>{{name}}</h2>
    <p>价格:{{price}}元</p>
    {{#if discount}}
    <span class="discount">限时折扣</span>
    {{/if}}
  </div>
</script>

<!-- 渲染结果挂载容器 -->
<div id="container"></div>
  • 原生JS调用渲染:
// 读取模板内容
var templateSource = document.getElementById('demo-template').innerHTML;
// 编译模板
var renderTemplate = Handlebars.compile(templateSource);
// 传入数据生成HTML
var renderResult = renderTemplate({
  name: '测试商品',
  price: 99,
  discount: true
});
// 插入到页面
document.getElementById('container').innerHTML = renderResult;

以上实现完全基于原生JS,不需要ES2015+语法,也不需要任何构建流程,适配简单HTML5项目的需求。

轻量替代方案

如果追求更轻量化的实现,你可以选择无依赖的小型模板引擎,甚至可以手写极简模板渲染函数满足基础需求:

// 极简模板渲染函数,支持基础变量替换
function simpleRender(tpl, data) {
  return tpl.replace(/{{(\w+)}}/g, function (_, key) {
    return data[key] || '';
  });
}

// 使用示例
var tpl = '<h3>{{title}}</h3><p>{{desc}}</p>';
var html = simpleRender(tpl, {
  title: '测试标题',
  desc: '测试描述内容'
});
document.getElementById('container').innerHTML = html;

如果需要支持简单的循环、条件判断,也可以选择同样无依赖、支持直接浏览器引入的轻量模板引擎,下载单文件到本地引入即可使用,无需额外配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:45:03