List of Body Markdown

Newbie question. How do you add markdown to each of the 4 text blocks below the header on the example sites product page for gatsby-starter-netlify-cms?

I thought it would be as simple as changing:
label: Text, name: text, widget: text
to :
label: Text, name: body, widget: markdown

But, I think this may not be possible as they are nested within:
{label: Intro, name: intro, widget: object, fields: [{label: Heading, name: heading, widget: string}, {label: Description, name: description, widget: text}, {label: Blurbs, name: blurbs, widget: list, fields: [{label: Image, name: image, widget: image}, {label: Text, name: text, widget: text}]}]}

(See: https://github.com/netlify-templates/gatsby-starter-netlify-cms/blob/master/static/admin/config.yml)

When I did this, my markdown didn’t appear at all or didn’t format at all. I then found out that I can only use body markdown at the top level, which I guess means removing the parent List widget and its parent object widget.

As my client will need to create the text blocks (and any additional ones) via the CMS admin. Am I forced to create all formattable elements as separate fields:? and dictate exactly how many text block they can have?

I’ve been trying to work this out all day, so any help is greatly appreciated.

Try this:

- label: Intro
  name: intro
  widget: object
  fields:
    - {label: Heading, name: heading, widget: string}
    - {label: Description, name: description, widget: text}
    - label: Blurbs
      name: blurbs
      widget: list
      fields:
        - {label: Image, name: image, widget: image}
        - {label: Text, name: text, widget: markdown}

I’m pretty sure the problem is that name: body is reserved to export markdown outside of the frontmatter block. It’s actually easier to leave the name as it is.

2 Likes

Thanks for the reply.

I did this but get markdown code on the CMS right preview panel and on the final website.

The docs say:

Please note: The markdown widget outputs a raw markdown string. Your static site generator may or may not render the markdown to HTML automatically. Consult with your static site generator’s documentation for more information about rendering markdown.

Is this the issue?

This post talks about the issue:

The gatsby-transformer-remark transform will only transform the markdown within the body of your .md file. It does not know to transform fields within your frontmatter .

As you can see from the query results above, your html is empty because the body is empty.

But it’s still not clear for to get markdownRemark on a list widget. Is it not possible?

Seems silly that any widget in a list can’t have markdown (or Richtext). Maybe I need to make this a collection instead? But then how do you put a collection withing a section of a page?

Getting closer after finding this post. https://github.com/gatsbyjs/gatsby/issues/5021#ref-commit-dcc0556

But still can’t work it out.

I still haven’t done this myself, but it’s a Gatsby issue - Netlify CMS will happily output markdown wherever you tell it to. Your issue is rendering markdown, which Gatsby doesn’t do out of the box yet. I don’t have time to dig in at the moment, unfortunately, but if I were going to, I would start with this comment and google my way through a manual solution:

You could also reach out to the various Gatsby support channels: Contributing to Gatsby | Gatsby

@LincMitch this worked for me to solve this issue:

import React from 'react'
import remark from 'remark'
import remarkHTML from 'remark-html'

const toHTML = value => remark()
                            .use(remarkHTML)
                            .processSync(value)
                            .toString()

const YourPreviewTemplate({ entry, getAsset }) => {
  const asMarkdown = entry.getIn(['data', 'something']) 
  const asHTML = toHTML(asMarkdown)
  // ... etc etc ...
}
2 Likes

@agervais, first, welcome to our Netlify community site and, second, thank you so much for sharing this solution! :slight_smile:

I’ve also mentioned your solution on the Gatsby issue which @erquhart linked to above.

1 Like

Solved my issue finally!

Thank you @agervais.

I actually just added this code to my page and wrapped the data from props before passing to the netlify-gatsby template “Content” component:

const toHTML = value => remark()
                    .use(remarkHTML)
                    .processSync(value)
                    .toString()

… Then in the component:

<PageContent className="content" content={toHTML(item.text)} />
1 Like

Hey man, would you mind sharing your config.yml file to give me a better understanding of how did you accomplish this? Thanks!

Hi @alfredo.gtz92

As stated above, the issue is not with the CMS, so config.yml is probably not what you’re looking for. You simply need to add a Markdown parser to Gatsby.

However, if you have a different issue, could you please explain it?

Hi @hrishikesh , I would like to include images in the multiple rich text / markdown fields and I wanted to see how the “item” field was configured in the .yml . Basically I don’t thing that the .toString() function is the right one for me. Do you have any thoughts on how to solve this?

Sorry @alfredo.gtz92, but I’m still confused. Even if you add images to multiple rich text fields, I’m not sure how that changes anything.

The Rich Text editor will convert anything you add there to Markdown (when you’re using Markdown file format), so as long as your SSG can parse the Markdown to give you a HTML output, that should work.

.toString() might or might not be the right one for you, but it depends on how your template is setup.

So I have my blog post pages displayed as follows:
blog-post.js

export default function BlogPost({ data }) {
  const post = data.markdownRemark
  return (
<Layout>
      <div className="blog-post-container">
        <div className="div-grey-post"></div>
        <div className="blog-post">
          <div className="top-post">
            <div className="featuredimage" ><img src={ post.frontmatter.featuredimage} loading="lazy" width="500" alt="" className="img-large-post"/></div>
            <div className="short-description">
                            
                <Heading color="dark">{post.frontmatter.title}</Heading>
                <div className="parpost light">{post.frontmatter.date}</div>
                <div className="tags-div">
                    {post.frontmatter.tags.map((tag) => (
                    <Link key={tag + `tag`} to={`/tags/${kebabCase(tag)}/`}><div className="div-tag">{tag}</div></Link> 
                    ))}</div>
                <p className="parpost">{post.frontmatter.short_description}</p>
            </div>
          </div>
          <div className="div-text-post" dangerouslySetInnerHTML={{ __html: post.frontmatter.mk1 }} />
          <div className="div-text-post" dangerouslySetInnerHTML={{ __html: post.frontmatter.mk2 }} />
        </div>
        <div className="div-grey-post"></div>
      </div>
      
    </Layout>

In this section I’m attempting to render 2 markdown fields in separate divs

<div className="div-text-post" dangerouslySetInnerHTML={{ __html: post.frontmatter.mk1 }} />
<div className="div-text-post" dangerouslySetInnerHTML={{ __html: post.frontmatter.mk2 }} />

It renders like this on my .md files
random.md

---
title: Huertos que funcionan en interiores
date: 2021-09-03T17:01:58.389Z
featuredimage: /assets/cultivo-en-casa-de-rabanitos.jpg
categoria: Naturaleza
tags:
  - cultivo
  - encasa
  - indoors
short-description: "En este artículo estudiaremos cómo se pueden cultivar
  hortalizas en el interior, incluso en invierno. Es importante utilizar mucha
  luz y agua cuando se cultivan verduras en el interior. También necesitarás un
  espacio luminoso que reciba al menos 6 horas de luz solar al día para obtener
  los mejores resultados. Estos son algunos consejos para elegir el tipo de
  hortaliza adecuado para cultivar en interiores:"
mk1: >-
  ### Tomate Cherry


  Los tomates cherry son unas de las plantas más fáciles de cultivar en macetas, pero recuerda que necesitan mucha luz solar y calor......

  ![to](/assets/1239x697.jpg "to")


  ### Lechuga


  La lechuga es ...

  ![le](/assets/lechuga-en-macetero.jpg "le")


  ### Zanahorias


  Para empezar, ...


  ![za](/assets/maceta-zanahorias-6dic14.jpg "za")
mk2: >-
  ### Albahaca


  La albahaca ...

  ![al](/assets/como-cuidar-la-albahaca.jpg "al")


 

As you can see, even though the .md is saving the info with the correct rich text format, I cannot make this render as a markdown widget.
I think that you already assumed this much.

What I would like is to have multiple markdown fields and separate them in different divs like this:
config.yml

    fields:
      - { name: title, label: Titulo, hint: Título llamativo y corto, required: true}
      - { name: date, label: Date, widget: datetime }
      - {label: "Imagen Principal", hint: Usar una imagen en alta resolucion y artistica, name: "featuredimage", widget: image, required: true}
      - { collection: categoria, valueField: categoria, searchFields: ["categoria"], displayFields: ["categoria"], widget: relation, name: categoria, label: Categoria, required: true, multiple: false, hint: Poner cateogoria a la que pertenece el tema. OBLIGATORIO}
      - {label: "Tags", name: "tags", widget: "list", hint: Separar con comas cada tag relacionado al post (ej. harrypotter, potterheads) poner al menos 3 tags por post, ideal 5, required: true}
      --------THIS SECTION BELOW WILL BE SEVERAL MARKDOWN FIELDS--------
- { name: mkd1, label: Post, widget: markdown }
      - { name: mkdy2, label: Post, widget: markdown }
      - { name: mkdy3, label: Post, widget: markdown }

. My question is, how do I do the parsing mentioned above in this case for several markdown fields?

I would appreciate a lot your help here

Hi @alfredo.gtz92,

Sorry about the delay here.

I am not full versed with Gatsby, but looking at your code, if you’re able to access each field from the Markdown front matter separately, this looks like something that should work. What exactly is the output that you’re getting?

Hey, I’ve been caught up on a different project, sorry about the delay.
I actually found a cool library to format my content as markdown:

import showdown from 'showdown'
const converter = new showdown.Converter()

and then, I just parse my frontmatter variables to html using converter like this:

<div className="div-text-post" dangerouslySetInnerHTML={{ __html: converter.makeHtml(post.frontmatter.mk1) }} />
<div className="div-text-post" dangerouslySetInnerHTML={{ __html: converter.makeHtml(post.frontmatter.mk2) }} />
<div className="div-text-post" dangerouslySetInnerHTML={{ __html: converter.makeHtml(post.frontmatter.mk3) }} />
<div className="div-text-post" dangerouslySetInnerHTML={{ __html: converter.makeHtml(post.frontmatter.mk4) }} />
<div className="div-text-post" dangerouslySetInnerHTML={{ __html: converter.makeHtml(post.frontmatter.mk5) }} />

If there’s a native way to do this, it would be interesting to try it.

From this:

mk2: >+
  ### 8.

  #### Rancho Calixto

  ![rancho calixto](/assets/cabanaqro.jpg "rancho calixto amealco")

  ##### Ubicación

  <div style="width: 100%"><iframe width="50%" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?width=50%25&amp;height=300&amp;hl=en&amp;q=20.16584478509557,%20-100.15599672327949+(Caba%C3%B1as%20Rancho%20Calixto)&amp;t=&amp;z=14&amp;ie=UTF8&amp;iwloc=B&amp;output=embed"></iframe></div>

  <br>Localizado en el municipio de Amelaco, ellos se describen como un servicio de hospedaje en cabañas, área para acampar en un bosque de pino- encino donde se crían venados y se protegen diferentes especies de aves

  <br>Puedes contactarlos en su facebook directamente [aquí](https://www.facebook.com/RanchoCalixtoAmealco)

I’m getting this output:

A funny thing is happening now… when I’m using this plugin somehow gatsby-image stopped working. My images are not being loaded as expected and the dimensions are not being handled neither. what do you suggest to debug these issues?

Gatsby images would probably not work as you’re using a different Markdown Parser that’s handling the conversion of images. You should probably ask Gatsby on what’s the best solution here.