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

如何用HTML模板结合JS动态生成内容?(PHP/JS/HTML项目)

客户端模板渲染(你要找的技术名称)

这就是你需要的技术——核心是把HTML模板和数据渲染逻辑分离,用JavaScript基于现成的HTML模板填充数据后插入页面,彻底解决PHP代码分散在视图里难以维护的问题。

方法一:使用HTML5原生<template>标签(推荐)

<template>是HTML5专门为模板场景设计的标签,里面的内容不会被页面自动渲染,仅作为结构容器存在,非常适合存放现成的HTML模板。

实现步骤:

  1. 在页面中定义商品模板和结果容器
<!-- 定义商品卡片模板 -->
<template id="product-template">
  <div class="product-card">
    <h3 class="product-name"></h3>
    <p class="product-price"></p>
    <img class="product-img" src="" alt="" />
    <button class="add-to-cart">加入购物车</button>
  </div>
</template>

<!-- 用来存放渲染完成的商品列表 -->
<div id="products-container"></div>
  1. 用PHP编写接口返回JSON格式的商品数据(比如单独创建get-products.php文件)
<?php
// 连接数据库并查询商品数据(这里用模拟数据示例)
$products = [
  ['name' => '无线耳机', 'price' => '299元', 'img_url' => '/images/headset.jpg'],
  ['name' => '智能手表', 'price' => '899元', 'img_url' => '/images/watch.jpg']
];

// 设置响应头为JSON格式
header('Content-Type: application/json');
echo json_encode($products);
?>
  1. 用JavaScript拉取数据、填充模板并插入页面
// 获取模板和容器元素
const template = document.getElementById('product-template');
const container = document.getElementById('products-container');

// 从PHP接口获取商品数据
fetch('get-products.php')
  .then(res => res.json())
  .then(products => {
    products.forEach(product => {
      // 克隆模板内容(template.content是文档片段,克隆后才能操作)
      const card = template.content.cloneNode(true);
      
      // 填充数据到模板的对应元素
      card.querySelector('.product-name').textContent = product.name;
      card.querySelector('.product-price').textContent = product.price;
      card.querySelector('.product-img').src = product.img_url;
      card.querySelector('.product-img').alt = product.name;
      
      // 将填充好的卡片插入容器
      container.appendChild(card);
    });
  })
  .catch(err => console.error('数据加载失败:', err));

方法二:用隐藏DOM元素做兼容式模板

如果需要兼容极老的浏览器(现在几乎不需要),可以用隐藏的<div>替代<template>:

<div id="product-template" style="display: none;">
  <div class="product-card">
    <h3 class="product-name"></h3>
    <p class="product-price"></p>
    <!-- 其他元素结构 -->
  </div>
</div>

JS逻辑和上述类似,只是克隆时直接操作这个div元素即可,无需访问content属性。

额外实用提示

  • 可以把所有模板集中放在单独的HTML文件(比如templates/product.html)里,用JS加载模板内容,进一步提升可维护性。
  • 如果需要复杂的模板逻辑(比如条件渲染、嵌套循环),可以尝试轻量模板库(如Handlebars、Mustache),但原生方案足够覆盖基础场景,适合自学阶段先掌握。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:15:36