So when using Drupal or Wordpress -- obviously you can write as much PHP in a template as you need, or in Wordpress for example, you can abstract that functionality away to the functions.php file. This allows for a quick way to add functionality without the overhead of setting up an entire plugin to do so.

I understand the benefits in Twig/Craft of not allowing that is to keep templates clean.

So, then what's the proper way of creating utility/helper functions in Craft that are callable in the templates? Would it be to create a "utility" module and just stick all of your utility functions in that module, or is there a better way to do it?

1 Answer 1


Yes, utility methods can go in a module that registers a custom Twig extension or extends the Craft variable. How you structure that depends on scope of the project (and personal preference):

  • For small projects with only a handful of utility functions, just stick them in a single extension in one module.
  • For medium projects with some custom functionality, I would create one separate module for each of those custom functionalities. Then each module can register Twig extensions (or extend the Craft variable) with functions and filters specific to that module / functionality. You can also stick to a single module, but with separate Twig extensions for related functions.
  • For really large projects or custom module with tons of stuff in it, I'll divide it further and put all the business logic and actual functionality in services classes. This way, those methods are also available to PHP if necessary (e.g. for usage in a Controller). The Twig extension then only provides methods that call the corresponding service classes, or provides access to the service class itself so you can call its methods from Twig.
  • Thanks -- seems a bit inconvenient I guess when you're trying to do something quick and dirty -- but I reckon setting up a module and having that separation of concerns isn't too many more steps than using something like functions.php -- and it provides a way to keep things a bit more organized. Feb 2, 2022 at 16:36
  • 1
    @kevindeleon Yes, once you're used to it setting up a module takes less than a minute. You can also use the pluginfactory website to create the module files, though I always find those come with a lot of stuff I don't need.
    – MoritzLost
    Feb 2, 2022 at 16:46
  • 1
    @kevindeleon And anything that discourages 'quick and dirty' is a plus in my opinion :D
    – MoritzLost
    Feb 2, 2022 at 16:46

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.