How do you create a custom Twig tag?
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();
}