1

Writing my first plugin. Scaffolded with Generator and is active (appearing in admin). This is where most tutorials leave you on your own so hoping to get some help calling a simple function in my templates.

In pluginname/src/Plugin.php I have the following function:

class Plugin extends BasePlugin
{
    public function hello() {
       return "Hello World";
    }
}

Template:

{{ pluginname.hello }}

Craft is not recognizing 'pluginname' as a variable so the function will not run. I'm obviously missing a critical concept here and hoping someone can point me in the right direction. Thanks.

1 Answer 1

1

Plugins don't provide any variables or functions to Twig by default, you need to do that explicitly. Check out the Extending Twig guide. You can find two good options there.

I would recommend using a Twig extension instead of extending the global craft variable. This is better in terms of separation of concerns, and easier to understand for new developers working on a project.

2
  • 1
    Thanks for replying. I'm going to pursue building a module instead which seems a bit simpler for learning purposes. Business Logic is a good tool with supporting documentation. I believe Generator also has an option to create a fully commented framework. Oct 20 at 17:57
  • @JasonMcKinney Starting with a module is definitely a good idea!
    – MoritzLost
    Oct 23 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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