How to get value of selected page template in Gutenberg editor?
-
15-04-2021 - |
Question
How to detect the value of selected page template in the edit page? I have used jQuery to select the page attribute select box but it is not working when we hide the editor sidebar; Because it removes the markup of that settings. I think it keeps data somewhere as we are able to bring back the sidebar without any change.
My code:
$('.editor-page-attributes__template select').val()
Is there any way to get the value when the sidebar is closed? Like any JavaScript variable in the page that updates when we change page template.
Note: I mean getting the value and use it in JavaScript without refreshing or updating the editor.
Solution
I slightly modified SkyShab's code, because it fired template change event on page load and it didn't fire when template was changed to default (since getEditedPostAttribute( 'template' ) is then '', which equals to null when testing for template change)
const { select, subscribe } = wp.data;
class PageTemplateSwitcher {
constructor() {
this.template = null;
}
init() {
subscribe( () => {
const newTemplate = select( 'core/editor' ).getEditedPostAttribute( 'template' );
if (newTemplate !== undefined && this.template === null) {
this.template = newTemplate;
}
if ( newTemplate !== undefined && newTemplate !== this.template ) {
this.template = newTemplate;
this.changeTemplate();
}
});
}
changeTemplate() {
// do your stuff here
console.log('template changed to ${this.template}');
}
}
new PageTemplateSwitcher().init();
OTHER TIPS
To get this value, use the wp.data module.
const template = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'template' );
Since this can be changed in the document settings, you would likely need to "subscribe" and run a callback whenever this changes.
For example:
const { select, subscribe } = wp.data;
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() {
// do your stuff here
console.log(`template changed to ${this.template}`);
}
}
new PageTemplateSwitcher().init();