Skip to content

Instantly share code, notes, and snippets.

@marijoo
Last active May 10, 2019
Embed
What would you like to do?
Render ACF blocks with Sage and blade templates
<?php
// add this function to Sage’s app/helpers.php
// inspired by nicooprat: https://gist.github.com/nicooprat/2c1a642d102425d3131037e5dc156361
/**
* Render callback for ACF $blocks
* @param array $block The block settings and attributes.
* @param string $content The block inner HTML (empty).
* @param bool $is_preview True during AJAX preview.
* @param (int|string) $post_id The post ID this block is saved to.
*/
function acf_block_render_callback($block) {
$slug = str_replace('acf/', '', $block['name']);
$classes = [$slug];
$id = sprintf('%s-%s', $slug, $block['id']);
if(!empty($block['anchor']))
$id = $block['anchor'];
if (!empty($block['className']))
$classes[] = $block['className'];
if (!empty($block['align']))
$classes[] = $block['align'];
$block['className'] = implode(' ', $classes);
echo template("blocks/${slug}", ['block' => $block]);
}
<?php
// add blocks to $blocks array with `name` and `title` being mandatory
/**
* Register Gutenberg blocks with ACF
* https://www.advancedcustomfields.com/resources/blocks/
*/
add_action('acf/init', function () {
if (function_exists('acf_register_block_type')) {
$blocks = [[
'name' => 'text-section',
'title' => __('Text Section', 'textdomain'),
'description' => __('Some description here', 'textdomain'),
'icon' => 'editor-textcolor',
'keywords' => ['text', 'hero', 'section']
]];
foreach ($blocks as $block) {
acf_register_block_type([
'name' => $block['name'],
'title' => $block['title'],
'description' => $block['description'] ?? null,
'render_callback' => '\App\acf_block_render_callback',
'category' => $block['category'] ?? 'formatting',
'icon' => $block['icon'] ?? 'layout',
'keywords' => $block['keywords'] ?? []
]);
}
}
});
<?php
// create a blade template for each block named by the block name
// i. e. resources/views/text-section.blade.php
<div id="<?php echo esc_attr($block['id']) ?>" class="<?php echo esc_attr($block['className']) ?>">
{{ get_field('title') }}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment