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

使用Nunjucks模板引擎无法渲染Unicode符号的解决方案咨询

Nunjucks渲染Unicode符号的解决办法

方案1:直接传递Unicode字符而非HTML实体

在服务端JS里,直接使用Unicode字符本身或者对应的转义序列,不需要传HTML实体代码:

// 写法1:直接写符号
const renderData = { statusIcon: '✔' };

// 写法2:使用Unicode转义序列(对应✔)
const renderData = { statusIcon: '\u2714' };

模板中直接渲染变量即可:

{{ statusIcon }}

Nunjucks的默认转义规则不会影响普通Unicode字符,能正常显示符号。

方案2:关闭变量的自动转义(适用于必须传HTML实体的场景)

如果一定要传递✔这类HTML实体字符串,可使用Nunjucks的safe过滤器,告诉模板该内容是安全的HTML,无需转义:

{{ statusIcon | safe }}

⚠️ 注意:仅当该数据是可信来源(比如后端生成,不是用户输入)时才用这个方法,避免XSS攻击风险。

方案3:服务端先解码HTML实体为字符

在服务端将HTML实体字符串转换为对应的Unicode字符,再传递给模板:

浏览器/前端环境解码

function decodeEntity(entity) {
  const textArea = document.createElement('textarea');
  textArea.innerHTML = entity;
  return textArea.value;
}

const statusIcon = decodeEntity('✔');
const renderData = { statusIcon };

Node.js服务端解码

如果是Node.js环境,可借助jsdom库实现解码:

const { JSDOM } = require('jsdom');
const dom = new JSDOM('');

function decodeEntity(entity) {
  const textArea = dom.window.document.createElement('textarea');
  textArea.innerHTML = entity;
  return textArea.value;
}

const statusIcon = decodeEntity('✔');
const renderData = { statusIcon };

之后模板中正常渲染{{ statusIcon }}即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:38:19