nystudio107 / craft-autocomplete

Provides Twig template IDE autocomplete of Craft CMS & plugin variables
MIT License
42 stars 4 forks source link

Add generator events #7

Closed bencroker closed 3 years ago

bencroker commented 3 years ago

It would be helpful to have events in AutocompleteVariableGenerator and AutocompleteTwigExtensionGenerator that make it easy to add properties to AutocompleteVariable and globals to AutocompleteTwigExtension respectively.

The usage would be as follows.

use nystudio107\autocomplete\generators\AutocompleteVariableGenerator;
use yii\base\Event;

Event::on(AutocompleteVariableGenerator::class,
    AutocompleteVariableGenerator::EVENT_BEFORE_GENERATE,
    function(Event $event) {
        $event->data[MyClass::class] = 'myClass';
    }
);
use nystudio107\autocomplete\generators\AutocompleteTwigExtensionGenerator;
use yii\base\Event;

Event::on(AutocompleteTwigExtensionGenerator::class,
    AutocompleteTwigExtensionGenerator::EVENT_BEFORE_GENERATE,
    function(Event $event) {
        $event->data['myValue'] = 'hello';
    }
);
khalwat commented 3 years ago

What would the use-case be here? Shouldn't it automatically be picking up any variables/globals?

bencroker commented 3 years ago

Yes, it should. But say I have a variable called myEntry that is defined in many of my templates (via a controller or in the template itself), it would be nice to be able to add autocompletion for it as follows.

Event::on(AutocompleteTwigExtensionGenerator::class,
    AutocompleteTwigExtensionGenerator::EVENT_BEFORE_GENERATE,
    function(Event $event) {
        $event->data['myEntry'] = 'new \craft\elements\Entry()';
    }
);
khalwat commented 3 years ago

IMO it'd be easier to just add a typehint to Twig than write PHP code to do the above:

{# @var cart \craft\commerce\elements\Order #}

e.g.: https://github.com/craftcms/commerce/blob/develop/example-templates/src/shop/cart/index.twig#L5

...but I'm not against the idea of having events anyway, so have at it!

bencroker commented 3 years ago

I didn't know that was even possible, very cool!

In my use-case, the variable is used in multiple templates across the site, so I think that adding it via an event makes sense, plus it can't hurt to provide events in general. Thanks for your input!

bencroker commented 3 years ago

Added in https://github.com/nystudio107/craft-autocomplete/commit/bba1951b7f12584c4c711aa5fb26cc76ff4a55e5, feel free to review.

khalwat commented 3 years ago

Did some minor cleanup (most unrelated to the changes). Should be good to go.

bencroker commented 3 years ago

Released in 1.0.5.