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

客户端渲染EJS局部模板报错:无法找到include文件求助

解决客户端EJS无法使用include复用局部模板的方案

客户端EJS无法读取服务器端文件系统中的局部模板,所以include方法失效,以下是几种无需重复编写卡片HTML代码的替代方案:

方案1:将局部模板内容作为全局变量传递到客户端

在服务器端读取局部模板的内容,渲染页面时把模板字符串传给客户端,客户端直接复用该模板渲染数据。

服务器端代码(Express示例)

const fs = require('fs');
const path = require('path');

// 读取info_card.ejs模板内容
const infoCardTemplate = fs.readFileSync(
  path.join(__dirname, 'views/partials/info_card.ejs'),
  'utf8'
);

// 渲染页面时将模板传递给客户端
app.get('/', (req, res) => {
  res.render('index', { infoCardTemplate });
});

页面模板(index.ejs)

在页面中注入模板字符串到全局变量:

<script>
window.infoCardTemplate = `<%- infoCardTemplate %>`;
</script>

客户端渲染代码

const update_info_cards = [
  {title: "title1", info: "info1"},
  {title: "title2", info: "info2"}
];

let html = '';
update_info_cards.forEach(card => {
  // 用全局模板渲染每个卡片数据
  html += ejs.render(window.infoCardTemplate, card);
});

// 将渲染后的HTML插入到页面容器中
document.getElementById('cards-container').innerHTML = html;

方案2:将局部模板嵌入页面的模板标签

在页面中用隐藏的<script>标签存放模板内容,客户端读取标签内容后复用渲染。

页面模板(index.ejs)

直接将info_card.ejs的内容嵌入到页面的模板标签中:

<script type="text/template" id="info-card-template">
  <!-- 这里是info_card.ejs的原始内容 -->
  <div class="info-card">
    <h2><%= title %></h2>
    <p><%= info %></p>
  </div>
</script>

客户端渲染代码

const update_info_cards = [
  {title: "title1", info: "info1"},
  {title: "title2", info: "info2"}
];

// 获取模板内容
const template = document.getElementById('info-card-template').innerHTML;
let html = '';

update_info_cards.forEach(card => {
  html += ejs.render(template, card);
});

document.getElementById('cards-container').innerHTML = html;

方案3:预编译EJS模板为客户端可用函数

使用EJS的命令行工具将局部模板预编译成JavaScript函数,客户端直接调用函数渲染数据,性能更优。

预编译模板

执行命令(需先全局安装EJS:npm install -g ejs):

ejs views/partials/info_card.ejs -o public/js/templates.js

客户端使用

引入预编译后的模板文件,直接调用生成的渲染函数:

<script src="/js/templates.js"></script>
<script>
const update_info_cards = [
  {title: "title1", info: "info1"},
  {title: "title2", info: "info2"}
];

let html = '';
update_info_cards.forEach(card => {
  // 调用预编译后的模板函数(函数名默认对应模板文件名,可自定义)
  html += info_card(card);
});

document.getElementById('cards-container').innerHTML = html;
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:31:06