Home Forums Gutenberg Setting the gutenberg block render callback dynamically


Setting the gutenberg block render callback dynamically

  • I am trying to tackle registering gutenberg blocks in a more object oriented way. My goal is to eventually only have to write something like this:

    $my_block = new GutenbergBlock($args);

    The problem I am running into is when I have to set the render_callback function. The function acf_register_block() wants a string of the function name to use as part of the arguments and I would like that function to be a method on the class or maybe set by a method on the class, maybe a method that returns the an anonymous function based on certain class properties. I want to dynamically give it something callable through a class function.

    I currently don’t see any way of doing that since the render callback function requires the $block variable as well as a couple others and those pieces of context are not present in my class context. I feel like if there was some way to hook into the render_callback process and add to the context I could also pass in other properties from my class to use in the render_callback.

    A practical example is when I want to use Timber and twig to render the block. I need to write something like this in my callback function:

    function my_render_callback($block, $content = '', $is_preview = false)
      $context = Timber::get_context();
      Timber::render($name_of_template_file, $context);

    Right now, I cannot get that $name_of_template_file to be dynamic because the render function is called in a completely different context than my class and I’d normally set that in my class. I’ve resorted to use a templating file structure that mirrors the name of the block to at least make it partially dynamic. This way I can write something like:

    $new_block = new GutenbergBlock(array('name' => 'my-cool-block'));

    Then in my callback function for that class I write:

    Timber::render('template-parts/' . $block[name] . '.twig');

    This at least makes it partially dynamic, but not all the way. I would love to not have to stick to a folder structure and just pass in that template variable dynamically somehow. But since the render callback is called in a different context than my class I cannot. At least not yet. I could be missing something completely obvious to a more skilled PHP programmer.

    That was a super long-winded post. I hope someone else knows a solution or at least sympathizes with my plight. Or at the very least even understands what I am saying.

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.