gray-matter icon indicating copy to clipboard operation
gray-matter copied to clipboard

Passing environment variable to the yaml file header

Open elaamrani opened this issue 2 years ago • 2 comments

Hello,

I would like to pass environment variables to the yaml file header. I tried the following:

---
name: ${{ process.env.ENV_VAR }}
name: `${{ process.env.ENV_VAR }}`
name: ${ENV_VAR}
name: $ENV_VAR
---

None of them worked. Would it be something possible to do?

Thanks!

elaamrani avatar Oct 27 '22 13:10 elaamrani

Actually you can do this when running gray-matter in Node using the JS parser:

---js
{
  NODE_ENV: process.env.NODE_ENV
}
---

Alternatively you could supply a custom parser engine:

import { javascript } from 'gray-matter/lib/engines.js'

const parsed = matter(str, {
  engines: {
    'embedded-js': (str, options) => {
      // naive implementation but you get the gist
      return javascript.parse(str.replace(/\$/g, 'process.env.'), options)
    }
  }
})

Then use it like so:

---embedded-js
{
  NODE_ENV: $NODE_ENV
}
---

webketje avatar Apr 25 '23 20:04 webketje

I would like to do something similar, accessing environment variables on astro docs front matter.

---
title: Page title for product name: {process.env.PUBLIC_ENV_APPNAME}
description: A description
sidebar:
  order: 3
---

Is this somehow possible using gray-matter?

YiannisBourkelis avatar Jan 07 '24 20:01 YiannisBourkelis