How to use gray-matter - 10 common examples

To help you get started, we’ve selected a few gray-matter examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github getgridea / gridea / src / server / posts.ts View on Github external
await Promise.all(results.map(async (result: any, index: any) => {
      const postMatter = matter(result)
      const data = (postMatter.data as any)

      data.title = formatYamlString(data.title)

      if (data && data.date) {
        if (typeof data.date === 'string') {
          data.date = moment(data.date).format('YYYY-MM-DD HH:mm:ss')
        } else {
          data.date = moment(data.date).subtract(8, 'hours').format('YYYY-MM-DD HH:mm:ss')
        }
      }

      // If there is a `tag` and it is of string type, it is corrected to array type.
      if (data && typeof data.tags === 'string') {
        const tagReg = /tags: [^\s[]/i
        const newTagString = data.tags.split(' ').toString()
github Veams / generator-veams / generators / app / templates / resources / templating / helpers / helper-partial.js View on Github external
function partial(name, context) {
		if (!Array.isArray(assemble.partials)) {
			assemble.partials = [assemble.partials];
		}

		var filepath = _.first(_.filter(assemble.partials, function (fp) {
			return path.basename(fp, path.extname(fp)) === name;
		}));

		// Process context, using YAML front-matter,
		// grunt config and Assemble options.data
		var pageObj = matter.read(filepath) || {};
		var metadata = pageObj.context || {};

		// `context`           = the given context (second parameter)
		// `metadata`          = YAML front matter of the partial
		// `opts.data[name]`   = JSON/YAML data file defined in Assemble options.data
		//                       with a basename matching the name of the partial, e.g
		//                       {{include 'foo'}} => foo.json
		// `this`              = Typically either YAML front matter of the "inheriting" page,
		//                       layout, block expression, or "parent" helper wrapping this helper
		// `opts`              = Custom properties defined in Assemble options
		// `grunt.config.data` = Data from grunt.config.data
		//                       (e.g. pkg: grunt.file.readJSON('package.json'))

		var omit = function (target) {
			return _.omit(target, 'pages', 'pagination');
		};
github evilz / vscode-reveal / src / EditorContext.ts View on Github external
get hasfrontConfig(): boolean {
    return (matter.test(this.getDocumentText()) as any) as boolean // bad d.ts file
  }
github FormidableLabs / spectacle / config / plugins / mdx-plugin / parse.js View on Github external
const parse = (src, options) => {
  const inlineModules = [];
  const { data, content } = matter(src);

  const separatedContent = normalizeNewline(content)
    /*
     * Set aside all inline JSX import and export statements from the MDX file.
     * When mdx.sync() compiles MDX into JSX, it will stub any component that doesn't
     * have a corresponding import. Therefore, we will re-add all of the imports/exports
     * to each slide before compiling the MDX via mdx.sync().
     */
    .replace(MOD_REG, (value, group1) => {
      if (!group1) {
        // group1 is empty, so this is not the import/export case we're looking for
        return value;
      } else {
        // found an inline export or import statement
        inlineModules.push(value);
        return '';
github nuxt-community / nuxtent-module / lib / content / page.ts View on Github external
get _rawData(): Nuxtent.Page.RawData {
    if (isDev || !this.cached.data.fileName) {
      const source = readFileSync(this.__meta.filePath).toString()
      const fileName = this.__meta.fileName
      this.cached.data.fileName = fileName
      if (fileName.search(/\.(md|html)$/) !== -1) {
        // { data: attributes, content: body } = matter(source)
        const result = matter(source, {
          excerpt: !!this.config.excerpt,
        })
        this.cached.data.attributes = result.data
        if (!!this.config.excerpt) {
          this.cached.data.attributes.excerpt =
            fileName.endsWith('md') &&
            this.config.markdown.parser &&
            result.excerpt
              ? this.config.markdown.parser.render(result.excerpt)
              : result.excerpt
        }
        this.cached.data.body.content = result.content
      } else if (fileName.search(/\.(yaml|yml)$/) !== -1) {
        this.cached.data.body.content = yaml.load(source)
      } else if (fileName.endsWith('.json')) {
        this.cached.data.body.content = JSON.parse(source)
github openmultiplayer / web / frontend / src / pages / docs / [[...path]].tsx View on Github external
context: GetStaticPropsContext<{ path: string[] }>
): Promise> {
  const { locale } = context;
  const route = context?.params.path || ["index"];

  let result: { source: string; fallback: boolean };
  const path = route.join("/");
  try {
    result = await readLocaleDocs(path, locale);
  } catch (e) {
    return {
      props: { error: `File ${path} (${locale}) not found: ${e.message}` },
    };
  }

  const { content, data } = matter(result.source);

  // TODO: plugins for admonitions and frontmatter etc
  // also, pawn syntax highlighting
  const mdxSource = await renderToString(content, {
    components,
    remarkPlugins: [admonitions],
  });

  return {
    props: {
      source: mdxSource,
      data,
      fallback: result.fallback,
    },
  };
}
github vuejs / vuepress / packages / @vuepress / shared-utils / src / parseFrontmatter.ts View on Github external
export = function parseFrontmatter (content: string) {
  return matter(content, {
    // eslint-disable-next-line @typescript-eslint/camelcase
    excerpt_separator: '',
    engines: {
      toml: toml.parse.bind(toml)
    }
  })
}
github documark / documark / lib / document.js View on Github external
Document.prototype.load = function () {
	// Get config and content
	var input = matter.read(this.file(), {
		delims: [''],
		lang: 'json',
	});

	this._config  = (input.data || {});
	this._content = input.content;

	// Load config.json if no front matter is available
	if (Object.keys(this._config).length === 0) {
		var configFile = path.join(this.path(), 'config.json');

		if (fs.existsSync(configFile)) {
			this._config = require(configFile);
		}
	}
};
github clarketm / hugo-elasticsearch / src / lib / hes.js View on Github external
readInputFile(filePath) {
    const ext = path.extname(filePath);
    const meta = matter.read(filePath, this.languageConfig);

    // Check if is a draft
    if (meta.data.draft) return;

    const tags = meta.data.tags || [];
    let content;

    // Content
    if (ext === ".md") content = removeMd(meta.content);
    else content = striptags(meta.content);

    // Uri
    let uri = `/${filePath.substring(0, filePath.lastIndexOf("."))}`.replace(`${this.baseDir}/`, "");

    if (meta.data.slug) uri = path.dirname(uri) + meta.data.slug;
github bcgov / devhub-app-web / app-web / plugins / gatsby-source-github-all / utils / plugins.js View on Github external
`\nFrontmatter key '${key}' is required but ${file.metadata.fileName} for source ${file.metadata.source} is missing it and will be ignored`,
        );
        // is there a defaultable value we can provide
      } else if (valueIsInvalid && DEFAULTS[key]) {
        frontmatter[key] = DEFAULTS[key]();
      }
    });
    // attach front matter properties to metadata
    file.metadata = {
      ...file.metadata,
      resourceTitle: frontmatter.title,
      resourceDescription: frontmatter.description,
      ignore: frontmatter.ignore,
    };
    // create 'new' md string with updated front matter
    file.content = matter.stringify(data.content, frontmatter);
    return file;
  }
  return file;
};

gray-matter

Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML front matter by default, but also has support for YAML, JSON, TOML or Coffee Front-Matter, with options to set custom delimiters. Used by metalsmith, assemble, verb and

MIT
Latest version published 4 years ago

Package Health Score

76 / 100
Full package analysis