Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I use block attributes in the template? #1

Closed
huubl opened this issue Dec 2, 2019 · 27 comments
Closed

How can I use block attributes in the template? #1

huubl opened this issue Dec 2, 2019 · 27 comments

Comments

@huubl
Copy link
Contributor

huubl commented Dec 2, 2019

Hi,

How to get the alignment, id and classes etc. to the block view? I tried:

@tylerwiegand
Copy link
Contributor

Same question -- the closest i came was returning $this->align; but it only (obviously) showed the contents of the register() array. I looked through the ACF Builder package and also found nothing.

If it's not clear what we're asking about, the "Advanced" dropdown on the sidebar for any block can generally accept a list of classes to add to the block container, and the alignment buttons atop the block are generally accessible with ACF blocks through $block['align'] and $block['className'] as shown here in section 3's code block.

Of course we can just add a Tab and add this functionality, but my boss in particular really wants this functionality so that our people that actually use the blocks to make the pages don't have to think too hard. For now I just added a tab called Advanced with a "Classes" field on everything, at least for this project.

I really did look through for awhile but I also am not exactly sure what I'm looking for, as I'm not sure how ACF exposes those attributes. I noticed you had a

    /**
     * The block alignment class.
     *
     * @var string
     */
    protected $align = '';

so I'm guessing some thought went toward it -- but I guess it could have been just a default setting to place on the block also... then again what's the point of having the setting if you can't actually use it in the block...

I tried to dump all the aforementioned variables from the block-name.blade.php render to no avail. If it's not supported currently perhaps you could point me toward where you think it should reside...?

Still loving the package!

@Log1x
Copy link
Owner

Log1x commented Dec 11, 2019

yeah $align is for setting what alignment the block allows during registering.

I didn't really think about $block - according to their examples, it should just auto-magically be available.

I will need to check, but perhaps the render_callback accepts a param for $block so we can pass it to the view.

@Log1x
Copy link
Owner

Log1x commented Dec 11, 2019

yeah it looks like I just need to add $block to the view() method (which is used in render_callback) and then pass 'block' => $block to the view.

Feel free to do a PR if that's enough to piece it together– otherwise I can try to push something tonight.

@tylerwiegand
Copy link
Contributor

Well, I gave it an honest try... I'm familiar with the Laravel view thing so I think I was doing it right (adding more data to the view). Everywhere I tried it I just got the $block not defined stuff...

I looked at the render_callback area in your package but I just don't understand how it works well enough I suppose to make out what your plan is =\

image

In order to understand it better I stared at this for awhile and ... it didnt take lol (advanced-custom-fields-pro/pro/blocks.php):
image

And this is where I was trying to add more data to the view (log1x/acf-composer/src/Block.php):
Screen Shot 2019-12-10 at 5 28 59 PM

I tried things like

echo view($view, [$this->with(), $block]);
echo view($view, [$this->with(), compact('block')]);
echo view($view, [$this->with(), ['block' => $this->block]);

to no avail... I thought I might find some inspiration from Stoutlogic's pack also but didn't see anything related to blocks, which makes sense I guess... (hmm, Log1x, Stoutlogic, any relation? hah!)

@Log1x Log1x closed this as completed in c055158 Dec 13, 2019
@Log1x
Copy link
Owner

Log1x commented Dec 13, 2019

sorry for the delay, pushed a release for $block

@huubl
Copy link
Contributor Author

huubl commented Dec 16, 2019

sorry for the delay, pushed a release for $block

Thanks, got it working!

@tylerwiegand
Copy link
Contributor

tylerwiegand commented Dec 16, 2019

This works and thank you very much @Log1x! I can't believe I was SO CLOSE and didn't get it lol...

While it does work, it does feel kind of bad to have all the block info in these pretty $this->stuff() calls returned to the view just like the composers and then need to add this to the top of every blade template for the blocks

<?php
use Illuminate\Support\Str;

$block   = $block ?? []; // just added to stop my IDE from squawking at me
$align   = 'align' . $block[ 'align' ];
$title   = 'any-prefix-you-want-' . Str::slug($block[ 'title' ]); // i guess i could use the name and remove "acf/" too...
$classes = $block[ 'className' ] ?? '';
?>

It would be nice of course to just add all that into the Block controller -- but it appears that the way it functions now we're just taking it from ACF and throwing it into the view along with the controller. It is certainly better, and again thank you for making that work, it really helps, but I think even you would agree "it would be nice if" we could do all this in the controller. I doubt there is going to be much demand though so I don't want to reopen anything... just note it here in case other people want to show interest.

Thanks again!! Love your packages and how the Sage 10 system feels so similar to a laravel project!

@Log1x
Copy link
Owner

Log1x commented Dec 16, 2019

No problem!

I do agree – I could make it happen by passing $block to something like $this->block so it is available in your controller.

Another thing I didn't think of and it'd be a small breaking change for you both, but perhaps change $block to an object?

@tylerwiegand
Copy link
Contributor

tylerwiegand commented Dec 16, 2019

Oh wow, I tried to add protected $block to Block.php and call it with $this->block but it said it was undefined -- So you have an idea of how to get $block from inside the Roots\view function, or include it some other way? I love it! Then I might even be able to use a Trait or something to process the block info and output it the same way on every extended Block class! Woo!

I would PREFER $block to be an object a great deal. All the !empty() or isset() calls really get to me lol...

@Log1x
Copy link
Owner

Log1x commented Dec 16, 2019

idk if it'll work but if you wouldn't mind testing 🐸

composer require log1x/acf-composer:dev-next

$block should be an object and $this->block should magically be a thing.

@tylerwiegand
Copy link
Contributor

Absolutely testing right now.

@tylerwiegand
Copy link
Contributor

It absolutely works, and you're right... it is magically a thing lol

@Log1x
Copy link
Owner

Log1x commented Dec 16, 2019

awesome. i appreciate it – ill push a release in a min

@Log1x
Copy link
Owner

Log1x commented Dec 16, 2019

should be good

@tylerwiegand
Copy link
Contributor

I'll try to get the classes that would be generated into a Trait or something -- from what I understand Wordpress default blocks output these classes so it would probably be desirable to have them output these as classes to a container div. Since it outputs a blade file I'm not suggesting wrapping it, just making it available with maybe something like this->blockClasses in the extended Block or something so you can just output that into the block view if desired. I also want to put a special prefix on my blocks so I'd like to account for that also...hmmm much to do much to do...

Thanks again ! =)

@Log1x
Copy link
Owner

Log1x commented Dec 16, 2019

If you haven't yet, you should check out native blocks. I spent months working with ACF blocks being intimidated by Gutenberg and now I greatly regret it. Native blocks are a god-send.

https://twitter.com/Log1x/status/1200040402679664640

@tylerwiegand
Copy link
Contributor

I love the idea of native blocks but as far as I understood it I needed to commit to using React to make the things and I'm mostly sold on Vue personally... I see the tweet mentions JSX though...

What I would love is to have a very cool editing experience that actually outputs what I see on the page inside the editing window. The trouble is, I PLAN on using Vuejs for a lot of my more complicated setups, so my next thing was going to be finding out how to get that to show up in the editor, which ... well that might not ever work lol... But I do love the idea of having the cool sliders and pickers that ACF blocks probably won't ever get.

Then everytime I make a new block I can just extract them and load in the ones that I want for any given project and leave the others out. As it stands now I'm generally making all new blocks for every project so the client can input data. The Preview is mostly useless since the final styles are never loaded into the editor because it messes with other styles. However, with Tailwindcss and PurgeCSS being used now in Sage 10 (due to Mix) I'm trying to codify a system where we use the ACF Composer to generate blocks more quickly, Blade templates to place the info in the structure I want, and Vue components for cool JS stuff, and Blade syntax in Vue Slots if needed (since I can't render blade inside the template).

I saw in the Sage chat that you were planning on doing Tailwindcss stubs for the Sage 10 interactive installer; I doubt there have been any plans to have Vue be a part of that ecosystem though since the WP editor is so closely tied to React...

If you're suggesting that there's a way I can ditch ACF without marrying React then I'm down right now. In fact a quick search showed me this (which I'm not sure even applies anymore due to the frequency of changes I saw for the last year or so in the WP Gutenberg world).

@Log1x
Copy link
Owner

Log1x commented Dec 16, 2019

I use Vue in all of my projects as well. I wasn't very keen on React and would prefer Vue as well– but you're right, there is not a sane way of approaching it.

But, with the API's available for Gutenberg– I think you'd surprise yourself on how easy you'd be able to jump into it and it's seriously fucking awesome.

I'll invite you to a repo with that product-block – you can see how things are "done right" considering most of what you'll find out there is 🗑.

@tylerwiegand
Copy link
Contributor

WHOA. this part especially makes me VERY happy

import { PanelBody, RangeControl } from '@wordpress/components';
import {
  RichText,
  MediaUpload,
  MediaPlaceholder,
  InspectorControls,
  URLInput,
  URLPopover,
  InnerBlocks,
} from '@wordpress/block-editor';

It looks like you can just USE any of the built in inputs...thats so nice.

Soooo... I just throw that repo base folder anywhere and import { blockName } from './folderLocation' and I'm done?

Wow...just having everything in one place would be nice enough to ditch ACF... AND I could still end up using Vue stuff from the blade file if I really wanted to, just understanding that it wouldn't show up in the editor...it'd certainly be an initial learn curve but over the holidays might be perfect to acquaint myself with this method...

I'll have to talk this over with the bossman. I was holding out hope that there was a possibility of rendering Vue components in the editor though...

Thanks a lot! I can probably get to trying this after this site is done in a day or so. I really want to dig into this...

@Log1x
Copy link
Owner

Log1x commented Dec 16, 2019

/**
 * Register the theme assets with the block editor.
 *
 * @return void
 */
add_action('enqueue_block_editor_assets', function () {
    if ($manifest = asset('js/manifest.asset.php')->get()) {
        wp_enqueue_script('app/editor.js', asset('js/editor.js')->uri(), $manifest['dependencies'], $manifest['version']);
        wp_add_inline_script('app/editor.js', asset('js/manifest.js')->contents(), 'before');
    }

    wp_enqueue_style('app/editor.css', asset('css/editor.css')->uri(), false, null);
}, 100);

/**
 * Register your block types with the block editor.
 *
 * @return void
 */
add_action('init', function () {
    return collect([
        'block/product',
        'block/product-overview'
    ])->each(function ($block) {
        register_block_type($block, [
            'render_callback' => function ($data, $content) use ($block) {
                return view(resource_path('views/blocks/' . Str::after($block, '/') . '.blade.php'), [
                    'data' => (object) $data,
                    'content' => ! empty(wp_strip_all_tags($content, true)) ? $content : null
                ]);
            }
        ]);
    });
}, 20);

Batteries required for Blade.

@Log1x
Copy link
Owner

Log1x commented Dec 16, 2019

If you're on the Roots Slack, drop me a DM and I can throw a few other helpers your way that bring things full circle.

https://www.patreon.com/rootsdev

@tylerwiegand
Copy link
Contributor

WHEW ok well i feel pretty dumb but it took me about 10 hours to get everything pointed at the right place (so pathetic lol)

for anyone else watching this tour de force, this is how I got everything 'plugged in':

i used the default sage10 mix structure, added your snippet (modified directories to match defaults, this part eluded me for far too long because im soooooo smaht) to the setup.php file:

/**
 * Register the theme assets with the block editor.
 *
 * @return void
 */
add_action('enqueue_block_editor_assets', function () {
    if ($manifest = asset('scripts/manifest.asset.php')->get()) {
        wp_enqueue_script('scripts/editor.js', asset('scripts/editor.js')->uri(), $manifest['dependencies'], $manifest['version']);
        wp_add_inline_script('app/editor.js', asset('scripts/manifest.js')->contents(), 'before');
    }

    wp_enqueue_style('app/editor.css', asset('styles/editor.css')->uri(), false, null);
}, 100);

/**
 * Register your block types with the block editor.
 *
 * @return void
 */
add_action('init', function () {
    return collect([
                       'block/product',
                   ])->each(function ($block) {
        register_block_type($block, [
            'render_callback' => function ($data, $content) use ($block) {
                return view(resource_path('views/blocks/' . Str::after($block, '/') . '.blade.php'), [
                    'data' => (object) $data,
                    'content' => ! empty(wp_strip_all_tags($content, true)) ? $content : null
                ]);
            }
        ]);
    });
}, 20);

Then in the editor.js file in the theme/resources/assets/scripts folder I added this to editor.js which starts blank:

import './blocks/product'

made a blocks folder and filled it with product\index.js that contains all the boilerplate from most example blocks you can find online

The blade view can live the in the views/blocks/product.blade.php directory as the snippet implies.

After all that though I did find the JSX syntax to be foreign enough to prevent me from actually using this right away -- I'm middling at Javascript at best(most frustrating thing I've ever done was make a few Google Chrome extensions lol).

I hope to have the time to re-visit this because i definitely think it's the superior method, but for now unfortunately I'll have to stick with the ACF Composer until I get said time =\

Thanks so much for the help!

@DuffmanCC
Copy link

Hi, I've finally find people who are using the same stack as me.

Sage + ACF blocks + Vue.js + Tailwindcss.

And I'm finding the same problems that you are. How would be possible to load Vue.js components into the Gutemberg editor wich is React?

My workflow is:

  • Register a new ACF block.
  • Assign fields to that block.
  • The block renders with no problems, tailwind works perfectly on the editor and on the front-end.
  • Blocks with Vue.js only works on the front-end so I can't render them on the editor creating a bad experience.

I've tried with vuera, a library to load Vue in React and React in Vue but I couldn't get it to work.

https://github.com/akxcv/vuera

https://jschof.com/gutenberg-blocks/proof-of-concept/vue-js-wordpress-using-vuera-to-run-vue-in-react/

Any help would be welcome.

@responsemktg
Copy link

I'll invite you to a repo with that product-block – you can see how things are "done right" considering most of what you'll find out there is 🗑.

I know this is an old thread, but as someone who :

  • Is a little intimidated about a switch to JSX from vanilla js / vue
  • Uses ACF extensively
  • Loves Blade
  • Confused with a lot of older/poorly written examples

I had two questions:

  1. What would it take to get an invite to this repo to have a peek at how it approached from a native perspective
  2. Do you still feel that 'ACF might as well be dead' to you after continued use?

Thanks, I really appreciate all the time you have taken to answer a lot of these questions!

@Log1x
Copy link
Owner

Log1x commented Oct 27, 2022

The product block would be far outdated now, probably.

I don't think ACF is dead at all and I use it for all of my blocks personally. It's fast, efficient, and like you I really like working with Blade and PHP.

I spoke too soon about ACF's block implementation initially. Once they got InnerBlock support and a lot more native functionality, things became full circle and it became a great developer experience (especially with ACF Composer).

@responsemktg
Copy link

I spoke too soon about ACF's block implementation initially. Once they got InnerBlock support and a lot more native functionality, things became full circle and it became a great developer experience (especially with ACF Composer).

That is great to hear. I inferred you might have felt this way due to the repo being actively maintained.
Ill admit, I did feel a slight sense of dread reading this thread, that after things finally coming into focus, my bud config and postCSS workflow taking off - that I may have backed the wrong horse. So its good to hear that in 2022 it's still a great alternative to going down the native path.

@Log1x
Copy link
Owner

Log1x commented Oct 27, 2022

Yeah, don't get me wrong – native blocks are awesome and extremely performant – but I'm just much more comfortable in PHP and I've never had any negative feedback on how the blocks function in the editor.

I think it's an overall smooth experience from both sides and everyone I've worked with who were coming from the classic editor / ACF flexible layouts to Gutenberg have been extremely happy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants