Search code examples
apostrophe-cms

How to add fields to specific page templates


I know how to add fields to pages by using apostrophe-custom-pages, but cannot figure out how to add field x only to page template a, and field y only to page template b in the beforeConstruct method. I have console.logged both the self and options parameters passed to the function, but never see the template name within the log (and therefore allowing me to run logic within the beforeConstruct method. Is there a way to accomplish this?


Solution

  • To have distinct schemas for different page types, you want an apostrophe-custom-pages subclass for each of those template types.

    in app.js or divided among each module's index.js

    const apos = require('apostrophe')({
      shortName: 'my-site',
      modules: {
    
        'default-pages': {
          extend: 'apostrophe-custom-pages',
          label: 'Default Page',
          name: 'default',
          addFields: [
            {
              name: 'customField',
              label: 'Special Label',
              type: 'string'
            }
          ]
        },
        'wacky-pages': {
          extend: 'apostrophe-custom-pages',
          label: 'Wacky Page',
          name: 'wacky',
          addFields: [
            {
              name: 'partyMode',
              label: 'Turn on party mode',
              type: 'boolean',
              choices: [
                { label: 'Yes', value: true },
                { label: 'No', value: false }
              ]
            }
          ]
        },
        ...
    

    Then in apostrophe-pages configuration you want to add those new subclasses as page choices to the types array

    in lib/modules/apostrophe-pages/index.js

      // ... other pages configuration
      types: [
        {
          name: 'default',
          label: 'Default'
        },
        {
          name: 'wacky',
          label: 'Wacky'
        },
    ]
    

    Then you want to create the corresponding templates as views in the apostrophe-pages module.

    lib/modules/apostrophe-pages /
    -- views /
    -- -- pages /
    -- -- -- wacky.html
    -- -- -- default.html