Skip to content

Instantly share code, notes, and snippets.

@marijoo
Last active January 4, 2024 17:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marijoo/4673905393d04ddf7c50b2a43d8d52cf to your computer and use it in GitHub Desktop.
Save marijoo/4673905393d04ddf7c50b2a43d8d52cf to your computer and use it in GitHub Desktop.
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>
@YolanCr-dev
Copy link

Thanks!

@chrillep
Copy link

chrillep commented Jan 4, 2024

there is a great helper for turning arrays to css classes :)

$block['className'] = implode(' ', $classes);

https://laravel.com/docs/9.x/helpers#method-array-to-css-classes

$block['className'] = Arr::toCssClasses($classes);

this or use tw merge https://github.com/YieldStudio/tailwind-merge-php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment