0

I'm using Netlify CMS for a React project. I'm able to render the whole file but I want to render only some specific parts of the markdown files like title, images, date etc.

I have made a markdown file search for the part that I want to extract and using substr and another method to extract just the part which I needed.

This solution is not dynamic. Like, if I want to get the description in place of the title, I'll have to rewrite that same code again which in my case would end up in too many lines of code.

This is the code that I'm using to get just the title.

let stringTitleSearchPattern = /title: /i;
let indexOfTitle = mdData.search(stringTitleSearchPattern);
let getTitleToEndFile = mdData.substr(indexOfTitle);
let lineBreak = /\n/;
let lineBreakIndex = getTitleToEndFile.search(lineBreak);
let startIndex = 7;
let endIndex = lineBreakIndex;
let title = getTitleToEndFile.substring(startIndex, endIndex);

All, these values can change depending upon what I want to retrieve from the markdown. I want to know whether is it possible to do so.

As I'm not very experienced with React, and not at all experienced with Netlify CMS and Markdown files. Please help find a solution.

Bhawna Saroha
  • 603
  • 1
  • 11
  • 28

1 Answers1

3

If you want to make it dynamic, you can pass a string a prop of what you want e.g title, description, etc.

Assumption: All other codes stays the same other than let stringTitleSearchPattern = /title: /i;

You can define a function, passing it stringTitleSearchPattern

const searchMarkdown = (searchSTring) => {
  let stringTitleSearchPattern = searchString;
  let indexOfTitle = mdData.search(stringTitleSearchPattern);
  let getTitleToEndFile = mdData.substr(indexOfTitle);
  let lineBreak = /\n/;
  let lineBreakIndex = getTitleToEndFile.search(lineBreak);
  let startIndex = 7;
  let endIndex = lineBreakIndex;
  let title = getTitleToEndFile.substring(startIndex, endIndex);
}

// call it
searchMarkdown(searchString: /title: /i)
searchMarkdown(searchString: /description: /i)

You can easily make more properties to search dynamically this way.

  • I can't make it completely dynamic as there are many things which are not fixed like startIndex and endIndex. Plus, does Netlify CMS only stores data as Markdown files or is there any other way the data can be stored? – Bhawna Saroha Apr 07 '19 at 18:11