2

In craft 2 I had a simple plugin that I used to run some php code. I could call the function like this.

{{ craft.pluginname.functionname }}

However I have been unable to do the same thing in craft 3. I have created a new plugin for craft 3. Moved my functions to the main plugin file in src.

Is there a new way to call a function from a plugin in craft 3?

Ok got it figured out.

author below = root plugin path in vendor folder

In main plugin file had to add

use author\pluginname\variables\variablename;
use craft\web\twig\variables\CraftVariable;

Updated init event to

Event::on(
    CraftVariable::class,
    CraftVariable::EVENT_INIT,
    function (Event $event) {
        /** @var CraftVariable $variable */
        $variable = $event->sender;
        $variable->set('pluginname', variablename::class);
    }
);

Created variables file in variables folder src/variables/variablename.php

namespace author\pluginname\variables;
use author\pluginname\mainClassName;
use Craft;

class variablename
{
    //Custom Functions Here
    public function test() {
        echo 'Test';
    }
}

Then from a template I was able to use

{{ craft.pluginname.test }}
2

You'll need to register your variable in your plugin's init() method, like this:

Event::on(
    CraftVariable::class,
    CraftVariable::EVENT_INIT,
    function (Event $event) {
        /** @var CraftVariable $variable */
        $variable = $event->sender;
        $variable->set('pluginname', PluginVariable::class);
    }
);

c.f.: https://docs.craftcms.com/v3/extend/extending-twig.html

  • Ok did that, looks like there is more to it than this... viewed another plugin I installed from app store. Created a variables directory with the variables file. Added use pluginroot/pluginname/variables/pluginvariable How do you call it using twig from a template file? Seems to be way more involved than craft2 apparently. – Bowenac Dec 13 '18 at 23:31
  • I might have just figured it out, will update later if I did, sorting out other deprecated errors. – Bowenac Dec 14 '18 at 0:00
  • Got it figured out, will update original post with more info on how I got it to work... for anyone else with same issue. Not a lot detailed docs on this stuff... – Bowenac Dec 14 '18 at 0:16
  • You can generate your plugin scaffolding at pluginfactory.io and it'll do all of this for you – andrew.welch Dec 15 '18 at 2:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.