Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Block.js file for Gist Gutenberg Block
/**
* BLOCK: wds-gist
*/
// Import CSS.
import './style.scss';
import './editor.scss';
const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
import Inspector from './inspector';
/**
* Register: aa Gutenberg Block.
*
* Registers a new block provided a unique name and an object defining its
* behavior. Once registered, the block is made editor as an option to any
* editor interface where blocks are implemented.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/
* @param {string} name Block name.
* @param {Object} settings Block settings.
* @return {?WPBlock} The block, if it has been successfully
* registered; otherwise `undefined`.
*/
registerBlockType( 'wds/block-wds-gist', {
// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __( 'WDS - GitHub Gist' ), // Block title.
icon: 'shield', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
keywords: [ __( 'GitHub' ), __( 'Gist' ) ],
attributes: {
username: {
type: 'string'
},
url: {
type: 'string'
}
},
// Determines what is displayed in the editor.
// https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/#edit
edit: function( props ) {
const {
attributes: { username, url },
className,
setAttributes
} = props;
let splitUrl = '';
if ( url ) {
splitUrl = url.split( '/' );
}
const index = splitUrl.length - 1;
const gistId = splitUrl[ index ];
const srcString = `https://gist.github.com/${ username }/${ gistId }.js`;
return [
<Inspector { ...{ setAttributes, ...props } } />,
<div className={ className }>Source: { srcString }</div>
];
},
// Determines what is displayed on the front-end.
// https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/#save
//
// For dynamic blocks, you can return null here and define a render callback function in PHP.
// https://wordpress.org/gutenberg/handbook/blocks/creating-dynamic-blocks/
save: function( props ) {
const {
attributes: { username, url },
className
} = props;
let splitUrl = '';
if ( url ) {
splitUrl = url.split( '/' );
}
const index = splitUrl.length - 1;
const gistId = splitUrl[ index ];
const srcString = `https://gist.github.com/${ username }/${ gistId }.js`;
return (
<div className={ className }>
<script src={ srcString } />
</div>
);
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment