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 built 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.


2 Answers 2


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

    // 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, 2015 at 15:37
  • @H2ONOCK yes; you absolutely need to do this with a plugin, and put the classes within its folder. Nov 7, 2015 at 17:47
  • Fantastic, nailed it, over the moon! Nice one, thanks! :)
    – H2ONOCK
    Nov 8, 2015 at 9:08

That's not the answer to this question, but it's kinda related...

Sometimes its worth to consider using {% do %} statement instead of using a custom tag. No need to handle Twig tokens and other complicated matters related to the custom tag.


{% do %} can use any variable defined by plugin/module - it just doesn't output anything.

Your Answer

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

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