3

For what do we need the templates folder in Gatsby project file structure? Can I use this folder for storing ordinary components that I reuse on a home page such as "hero" or "info" components ets?

2 Answers2

4

The /src/templates folder doesn't do anything in particular (unlike the /src/pages folder for example), but it's normally used to store templates for pages that you're creating programatically. You could also simply store any page templates in a /src/components folder and remove /src/templates altogether, if you prefer.

Robin Métral
  • 3,099
  • 3
  • 17
  • 32
2

The purpose of /templates folder is to store templates (huh?), that is to say, all pages that would be created programmatically via createPage API and will share the same internal structure (components, header, footer, etc) but different content. Ideally, you will have there a post.js, legal.js (for all terms and conditions, terms of service, etc) in order to share the same structure for all your retrieved data from CMS, like:

  posts.forEach(({ node }, index) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/templates/posts.js`),
      context: { id: node.id },
    })
  })
}

It is only used to structure the code and create a more clean structure. For me, rather the Robin Métral answer I would keep it, if you don't use it and remains empty the file won't be committed but is really useful and the programmatic page creation is one of the main advantages of Gatsby, but also is really helpful to keep a clean and clear structure.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
  • 3
    For the record, I agree it's a helpful folder to keep if you're using templates, but [the official example for programmatically creating pages](https://www.gatsbyjs.org/docs/mdx/programmatically-creating-pages/) stores the template in `/src/components`. Therefore it's a matter of personal preference. – Robin Métral Jun 09 '20 at 06:48
  • 2
    Totally agree with you, it's usually a matter of personal preference. However, depending on what page are you looking it shows `/component` or `/template`, like https://www.gatsbyjs.org/docs/creating-and-modifying-pages/ shows. So, my personal preference is to keep and maintain the logic and folder structure. – Ferran Buireu Jun 09 '20 at 07:05