6

Say I'm building a plugin that adds user memberships to the website. I want to check on my front end templates that user's membership is active and I have build the functionality inside the plugin to do this.

How do I use a tag like {% requireMembership %} in place of the normal {% requireLogin %} to call the function that I've built? I thought it would be simple but can't find documentation on this anywhere.

11

There are two classes behind each Twig tag: a Token Parser and a Node.

The Token Parser is responsible for actually parsing the template, once Twig has tokenized it, and returning your Node class to represent it. The Node class is responsible for compiling itself into actual PHP code.

{% requireLogin %} is about as simple as it gets, because it doesn’t have to worry about parsing parameters, expressions, sub-content, etc. You can use its Token Parser and Node classes as a starting point - they’re located in craft/app/etc/templating/twigextensions/.

Once you’ve created those classes, you will need to create a Twig Extension, which will be used to connect your TokenParser to Craft’s instance of Twig. Give it a getTokenParsers() method which returns an instance of your Token Parser class (example).

(Note that if you use the Craft namespace in these clasess, you will need to prefix all of Twig’s class names with \, e.g. \Twig_TokenParser.)

Finally you need to register your Twig Extension from your plugin’s primary class using the addTwigExtension hook:

public function addTwigExtension()
{
    // Import the Twig Extension, Token Parser, and Node classes
    Craft::import('plugins.mypluginfolder.MyTwigExtension');
    Craft::import('plugins.mypluginfolder.MyTokenParser');
    Craft::import('plugins.mypluginfolder.MyNode');

    // Return a new instance of it
    return new MyTwigExtension();
}
  • Wow, thanks for this...I wouldn't have EVER got to that answer! Can I just check though... if I modify files inside craft/app/etc/templating will they get overwritten when craft updates? – H2ONOCK Nov 7 '15 at 15:37
  • @H2ONOCK yes; you absolutely need to do this with a plugin, and put the classes within its folder. – Brandon Kelly Nov 7 '15 at 17:47
  • Fantastic, nailed it, over the moon! Nice one, thanks! :) – H2ONOCK Nov 8 '15 at 9:08

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.