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

在Pug模板中使用i18n:调用compileFile时__函数未找到报错

解决Pug compileFile调用时i18n '__'函数未找到的问题

这个问题我之前也碰到过,核心原因其实很明确:当你直接调用Pug的compileFile方法时,并没有经过Express的i18n.init中间件处理,模板里的__函数自然不会被自动注入到编译上下文里。

正常通过Express的res.render渲染模板时,i18n.init中间件会自动把__函数挂载到响应对象的locals中,Pug渲染时能直接读取到;但compileFile是Pug的底层编译方法,完全脱离了Express的请求/响应上下文,所以模板里的__就成了未定义的函数。

下面给你两个可行的解决方案:

方案一:手动传递i18n翻译函数到模板上下文

在调用编译后的模板函数时,手动把i18n的翻译函数作为参数传入,让模板能直接访问到:

const pug = require('pug');
const i18n = require('i18n');

// 编译模板文件
const compiledTemplate = pug.compileFile(path.resolve('path/to/your/template.pug'));

// 手动传入i18n相关上下文
const html = compiledTemplate({
  __: i18n.__, // 使用全局翻译函数,若需指定locale可绑定:i18n.__.bind({ locale: 'gr' })
  locale: i18n.getLocale()
});

如果是在Express的请求处理流程里调用compileFile,可以直接用当前请求上下文里的__函数,这样能自动匹配请求对应的locale:

app.get('/custom-render', (req, res) => {
  const compiledTemplate = pug.compileFile(path.resolve('path/to/template.pug'));
  const html = compiledTemplate({
    __: req.__ // 复用请求上下文的翻译函数,自动适配当前请求的locale
  });
  res.send(html);
});

方案二:给Pug全局注册i18n辅助函数

如果你希望所有通过compileFile编译的模板都能直接使用__函数,可以给Pug的全局上下文注册这个函数:

const pug = require('pug');
const i18n = require('i18n');

// 全局注册__函数,所有编译后的模板都能直接调用
pug.locals.__ = i18n.__;

// 后续调用compileFile编译的模板无需额外传参
const compiledTemplate = pug.compileFile(path.resolve('path/to/template.pug'));
const html = compiledTemplate();

不过这种方式依赖全局的i18n配置,如果需要动态切换locale,方案一更灵活,因为可以根据场景绑定不同的locale实例。

另外你提到正常渲染模板时一切正常,说明你的i18n基础配置是没问题的,不用额外调整objectNotation这类参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:30:55