Open anubisthejackle opened 8 months ago
The create-block script should be fairly universal in what it scaffolds to meet most requirements for building blocks. Having a render-feed may not meet the needs in most cases. Therefore if there were to be a render-feed template it would have to be an option provided by a prompt in the create block script.
Even so, as @goodguyry pointed out an eloquent way to switch the render.php
file based on certain conditions using a filter.
Here is a simple example:
add_filter( 'block_type_metadata', 'filter_block_type_metadata_for_feed' );
/**
* Filter block metadata to override the render file for a feed.
*
* @param array $metadata Metadata for registering a block type.
* @return array Modified block metadata.
*/
function filter_block_type_metadata_for_feed( $metadata ) {
if ( ! is_feed() ) {
return $metadata;
}
// Bail if the block doesn't have a render file.
if ( empty( $metadata['file'] ) ) {
return $metadata;
}
/**
* The `render-feed.php` file should be located in the same directory as the block.json file.
*/
$render_feed_filename = 'render-feed.php';
$path = wp_normalize_path(
realpath(
dirname( $metadata['file'] ) . '/' . $render_feed_filename
)
);
// Use the feed specific render file, if one exists.
if (
( 0 === validate_file( $path ) || 2 === validate_file( $path ) ) && file_exists( $path )
) {
$metadata['render'] = "file:{$render_feed_filename}";
}
return $metadata;
}
This may be a decision a developer decides to make when building the block and can be fairly easily implemented instead of adding complexity to the create block script to output this alternative. It certainly could be done but the use case should be broad in my opinion.
I'd say it's also worth considering the block's save
method as the first fallback for cases like feeds, as described here: https://twitter.com/schlessera/status/1537465743985590273
Adding static content in the save()
method doesn't preclude the use of a more-specific render file, but in some cases it might amount to the same thing.
Description
I would like to see a secondary render file created to allow block developers to differentiate the view of a block based on where that block is rendered, whether in content, or in an RSS feed, for example.
I imagine this structure like so:
render.php
as they are currently.render.php
that checks if the loaded page is a feed.render-feed.php
file and return.render-default.php
file and return.render.php
file, and newrender-[service].php
files can be added.Use Case
Sometimes we create blocks that are really placeholders for React apps. When this happens, these blocks will only render the React root element in the feed, but will obviously not render the React app in feed viewers, due to no client JS being executed.
This secondary file allows us to pre-define a layout for the block to show in feeds that is appropriate. Beyond that, it will provide a standardized example of adding additional views for things like Apple News feeds, etc.