Templates are used to create single pages for nodes in a collection. Nodes need a corresponding page in order to be presented on its own URL.
The example below shows you how to setup route and template for a collection named Post
. A component located at src/templates/{Collection}.vue
will be used as template if no component is specified.
// gridsome.config.js
module.exports = {
templates: {
Post: '/blog/:year/:month/:title',
}
}
Specify a custom component path:
// gridsome.config.js
module.exports = {
templates: {
Post: [
{
path: '/blog/:year/:month/:title',
component: './src/other/location/Post.vue'
}
]
}
}
Setup multiple templates for a collection:
// gridsome.config.js
module.exports = {
templates: {
Product: [
{
path: '/product/:slug',
component: './src/templates/Product.vue'
},
{
name: 'reviews',
path: '/product/:slug/reviews',
component: './src/templates/ProductReviews.vue'
}
]
}
}
Template paths are available in the GraphQL schema with a path
field. Use a to
argument for getting paths to additional templates for a collection.
query ($id: ID!) {
product(id: $id) {
path # path to the default template
path(to:"reviews") # path to the reviews template
}
}
Available template options are:
Path parameters are slugified by default, but the original value can be used by adding a _raw
suffix, eg. :title_raw
. Access values in deep objects or arrays by separating properties or indexes with double underscores (__
). The date
field has a set of shorthand helpers; :year
, :month
and :day
.
:id
resolves to node.id
:value
resolves to node.value
(slugified value):value_raw
resolves to node.value
(original value):object__value
resolves to node.object.value
:array__3__id
resolves to node.array[3].id
The path
option can be a function, which receives the node as the first argument and returns a path.
// gridsome.config.js
module.exports = {
templates: {
Post: [
{
path: (node) => {
return `/product/${node.slug}/reviews`
}
}
]
}
}
Each node will get a path
field in the GraphQL schema which contains the generated URL.
Pages generated from the templates
configuration will have the node id
available as a query variable in the page-query
block. Use the $id
variable to get the node for the current page:
<template>
<div>
<h1 v-html="$page.post.title" />
<div v-html="$page.post.content" />
</div>
</template>
<page-query>
query ($id: ID!) {
post(id: $id) {
title
content
}
}
</page-query>
Other node fields are also available as query variables. Access values in deep objects or arrays by separating properties or indexes with double underscores (__
).
$id
resolves to node.id
$value
resolves to node.value
$object__value
resolves to node.object.value
$array__3__id
resolves to node.array[3].id
The metaInfo
option must be a function in order to access the query results:
<script>
export default {
metaInfo() {
return {
title: this.$page.post.title
}
}
}
</script>