Sanity initial value template not working in structure - "Template not defined" warning

4 replies
Last updated: Jun 25, 2021
Hi! I'm trying to use a initial value template in a structure like this example . But the value is not set, and in the browser console there is a warning "Template 'article-by-product' not defined, using empty initial value".What am I doing wrong ?
AI Update

I can see the confusion here! The error "Template 'article-by-product' not defined, using empty initial value" means your template isn't properly registered in your Studio configuration. Let me show you the correct way to set this up.

The Solution

Initial Value Templates need to be defined in your sanity.config.ts file using the schema.templates property. Here's the proper setup:

// sanity.config.ts
import {defineConfig} from 'sanity'

export default defineConfig({
  // ... other config
  schema: {
    types: [
      // your schema types here
    ],
    templates: (prev) => [
      ...prev,
      {
        id: 'article-by-product',
        title: 'Article by Product',
        schemaType: 'article',
        parameters: [{name: 'productId', type: 'string'}],
        value: (params) => ({
          product: {
            _type: 'reference',
            _ref: params.productId
          }
        })
      }
    ]
  }
})

Then in your Structure Builder, you can reference this template:

S.listItem()
  .title('New Article')
  .child(
    S.documentTypeList('article')
      .initialValueTemplates([
        S.initialValueTemplateItem('article-by-product', {
          productId: 'some-product-id'
        })
      ])
  )

Key Points

  1. Templates go in schema.templates: This is where Sanity looks for template definitions. The Initial Value Templates documentation confirms this is the correct location.

  2. Always spread ...prev: This preserves the default templates that Sanity provides

  3. The template ID must match: The id you define in schema.templates must exactly match what you reference in your Structure Builder with initialValueTemplateItem()

  4. Parameters are optional: You can pass parameters to make templates dynamic and context-aware

  5. The value function: This returns the initial values for your new document. It can be synchronous (as shown) or asynchronous if you need to fetch data

Common Mistakes

The most common issue is not defining the template in schema.templates at all, or defining it in the wrong place (like in document.newDocumentOptions, which is for customizing the UI options shown to users, not for defining templates themselves). The Structure Builder is just for using templates - the actual template definitions must live in your schema configuration.

Another common mistake is a typo in the template ID - make sure the string you pass to initialValueTemplateItem() exactly matches the id in your template definition.

Restart Required

After adding templates to sanity.config.ts, make sure to restart your dev server. Changes to the config file require a restart to take effect.

Dynamic Values Example

If you need to fetch data or use async logic, your value function can be async:

{
  id: 'article-by-product',
  title: 'Article by Product',
  schemaType: 'article',
  parameters: [{name: 'productId', type: 'string'}],
  value: async (params) => {
    // You can even fetch data here if needed
    return {
      product: {
        _type: 'reference',
        _ref: params.productId
      },
      publishedAt: new Date().toISOString()
    }
  }
}

For more examples of using templates with parent-child relationships, check out the parent-child taxonomy guide which shows practical implementations.

Show original thread
4 replies
Here is the code in the deskStructure.js file:
S.documentTypeList('product')
            .title('Product')
            .child(productId =>
              S.list()
                .title('Content')
                .items([
                  S.listItem({
                    id: 'articles-by-product',
                    title: 'All articles',
                    child: () => 
                      S.documentTypeList('docArticle')
                        .title('All articles')
                        .filter('_type == "docArticle" && references($productId)')
                        .params({ productId })
                        .initialValueTemplates([
                          S.initialValueTemplateItem('article-by-product', { productId })
                        ])
                  }),
The initialValueTemplates.js file:

import T from '@sanity/base/initial-value-template-builder';

export default [
    ...T.defaults(),
    
    T.template({
        id: 'article-by-product',
        title: 'Documentation Article',
        description: 'Article for a specific product',
        schemaType: 'docArticle',
        parameters: [{name: 'productId', type: 'string'}],
        value: params => ({
          product: {_type: 'reference', _ref: params.productId}
        })
      })
  ]
And the sanity.json file:

"parts": [
    {
      "name": "part:@sanity/base/schema",
      "path": "./schemas/schema"
    },
    {
      "name": "part:@sanity/desk-tool/structure",
      "path": "./deskStructure.js"
    },
    {
      "name": "part:@sanity/base/initial-value-templates",
      "path": "./initialValueTemplates.js"
    }
  ]
did you restart the server after editing sanity.json?
Initial values will not be set on fields in existing documents. Have you tried creating a new document to see if fields are populated?
user B
newbie's fail, the restart did the job, thanks!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?