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

NodeJS/KeystoneJS项目中Nunjucks全局变量设置与访问问题求助

Fixing Nunjucks Global Variable Access in KeystoneJS

Hey there, let's work through this Nunjucks global variable issue you're hitting in your KeystoneJS project. The core problem here is that you're creating separate Nunjucks environments in Keystone's setup and your Login.js route—so the global variable you added in one doesn't exist in the other. Here's the proper way to handle this:

1. Use Keystone's Built-In Nunjucks Configuration

KeystoneJS manages its own Nunjucks environment under the hood, so you don't need to create a separate one to add globals. Instead, define your global variables directly in Keystone's main config file (usually keystone.js or config/keystone.js):

// In your Keystone config file
keystone.set('nunjucks options', {
  globals: {
    provision_uri: process.env.PROVISION_URI || 'http://your-default-uri:port'
  }
});

This injects provision_uri into the single, shared Nunjucks environment that Keystone uses for all template rendering.

2. Don't Create a New Nunjucks Environment in Your Route

In your Login.js route handler, stop initializing a fresh Nunjucks environment. Instead, use Keystone's existing environment via either:

  • Keystone's res.render() method: This automatically uses the pre-configured environment with your globals included:
    // Login.js route example
    exports.login = (req, res) => {
      // provision_uri is already available in the template
      res.render('login', {
        // Add any local template variables here
      });
    };
    
  • Directly access Keystone's Nunjucks environment: If you need to interact with the environment programmatically, fetch it via Keystone's getter:
    const nunjucksEnv = keystone.get('nunjucksEnv');
    // Now you can access nunjucksEnv.globals.provision_uri
    

3. Why Your Original Approach Failed

When you created a new Nunjucks environment in Login.js, it was a completely separate instance from the one you configured in Keystone. The two environments don't share globals, which is why you got the Error: global not found: provision_uri message. Keystone is designed to manage this environment for you—reusing it ensures consistency across your app.

4. Verify the Global Variable Works

In your Nunjucks templates, you can now use the global directly without passing it as a local variable:

<!-- Example in your HTML view -->
<link rel="stylesheet" href="{{ provision_uri }}/css/styles.css">
<script src="{{ provision_uri }}/js/app.js"></script>

This approach is far cleaner than your temporary workaround, especially since you're working on a project where consistency across views is important.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:16:26