Skip to content

EJS 指南

This content is not available in your language yet.

{
"templateEngine": "ejs"
}

如果 config.json 中未声明 templateEngine,默认使用 EJS(为旧版兼容)。

EJS 有三种核心输出方式:

<% /* 执行代码,不输出 */ %>
<%= value %> <%# 转义输出:HTML 会被转义 %>
<%- value %> <%# 原始输出:直接输出 HTML %>

EJS 使用 camelCase 命名,与 Jinja2 一致:

<h1><%= config.siteName %></h1>
<p><%= config.siteDescription %></p>
<%# 文章内容是 HTML,必须用 <%- 原始输出 %>
<%- post.content %>
<%# 主题配置 %>
<%= theme_config.primaryColor %>
<% posts.forEach(function(post) { %>
<article>
<h2><a href="<%= post.link %>"><%= post.title %></a></h2>
<time><%= post.date %></time>
</article>
<% }); %>
<% if (post.feature) { %>
<img src="<%= post.feature %>" alt="<%= post.title %>">
<% } %>
<% if (posts.length > 0) { %>
<%# 显示文章列表 %>
<% } else { %>
<p>暂无文章</p>
<% } %>
<%- include('partials/header') %>
<main>内容区域</main>
<%- include('partials/footer') %>
<%# 传递数据给局部模板 %>
<%- include('partials/head', { title: post.title }) %>

Gridea Pro 中的 EJS 运行时不支持 Node.js 的 require() 函数。你无法引入外部 npm 包或自定义模块:

<%# 错误 -- 会报运行时错误 %>
<% var moment = require('moment'); %>
<%# 正确 -- 使用原生 JavaScript %>
<% var year = new Date().getFullYear(); %>

与其他引擎一致,post.date 已是格式化后的字符串:

<%# 正确 %>
<time><%= post.date %></time>
<%# 不必要 -- date 已经格式化 %>
<time><%= new Date(post.date).toLocaleDateString() %></time>

如果你正在维护旧版 EJS 主题,建议逐步迁移到 Jinja2。核心对照:

EJSJinja2 (Pongo2)
<%= value %>{{ value }}
<%- html %>{{ html|safe }}
<% if (x) { %>{% if x %}
<% } %>{% endif %}
<% arr.forEach(function(item) { %>{% for item in arr %}
<% }); %>{% endfor %}
<%- include('partials/x') %>{% include "partials/x.html" %}
{% extends "base.html" %}

迁移步骤:

  1. config.jsontemplateEngine 改为 "jinja2"
  2. 逐个文件转换语法
  3. include 组装升级为 extends + block 继承
  4. 使用预览功能验证每个页面

完整变量列表请查阅模板变量参考