Created
May 4, 2018 21:01
Star
You must be signed in to star a gist
Gutenberg Page Template Switcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gql from 'graphql-tag' | |
import { client } from '../utils/apollo-client' | |
const { parse } = wp.blocks; | |
const { select, subscribe, dispatch } = wp.data; | |
const GET_PAGE_BLOCK_TEMPLATE = gql` | |
query GET_PAGE_BLOCK_TEMPLATE($id: ID!, $template: String) { | |
page( id: $id ) { | |
blockTemplate( pageTemplate: $template ) | |
} | |
} | |
`; | |
class PageTemplateSwitcher { | |
constructor() { | |
this.template = null; | |
} | |
init() { | |
subscribe( () => { | |
const newTemplate = select( 'core/editor' ).getEditedPostAttribute( 'template' ); | |
if ( newTemplate && newTemplate !== this.template ) { | |
this.template = newTemplate; | |
this.changeTemplate(); | |
} | |
} ); | |
} | |
changeTemplate() { | |
const { resetBlocks } = dispatch('core/editor'); | |
const postType = select( 'core/editor' ).getEditedPostAttribute( 'type' ); | |
const id = select( 'core/editor' ).getEditedPostAttribute( 'id' ); | |
if ( postType && id ) { | |
const globalId = postType && id ? btoa( postType + ':' + id ) : null; | |
client.query({ | |
query: GET_PAGE_BLOCK_TEMPLATE, | |
variables: { | |
id: globalId, | |
template: this.template | |
} | |
}).then( result => { | |
console.log( result ); | |
if ( result.data && result.data.page && result.data.page.blockTemplate ) { | |
resetBlocks( parse( result.data.page.blockTemplate ) ); | |
} | |
}); | |
} | |
} | |
} | |
new PageTemplateSwitcher().init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also relevant, using React:
WordPress/gutenberg#8162 (comment)
https://discourse.roots.io/t/gutenberg-body-class-elements-by-template/15310