jonschlinkert / gray-matter

Smarter YAML front matter parser, used by metalsmith, Gatsby, Netlify, Assemble, mapbox-gl, phenomic, vuejs vitepress, TinaCMS, Shopify Polaris, Ant Design, Astro, hashicorp, garden, slidev, saber, sourcegraph, and many others. Simple to use, and battle tested. Parses YAML by default but can also parse JSON Front Matter, Coffee Front Matter, TOML Front Matter, and has support for custom parsers. Please follow gray-matter's author: https://github.com/jonschlinkert
https://github.com/jonschlinkert
MIT License
3.97k stars 138 forks source link

Passing environment variable to the yaml file header #153

Open elaamrani opened 2 years ago

elaamrani commented 2 years ago

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!

webketje commented 1 year ago

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
}
---
YiannisBourkelis commented 10 months ago

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?