-
Notifications
You must be signed in to change notification settings - Fork 70
Custom Twig extensions (filters, functions, tags, etc.)
Ever seen this?
Fatal error: Uncaught Twig_Error_Syntax: Unknown "SOMETHING" function.
Sometimes you need to add a custom Twig extension to Pattern Lab - particularly when using Drupal, which ships with its own. Oftentimes you don't even need Pattern Lab to do anything with it, you just need it to ignore the function or just pass a string. The good news is we have already done this by default for many of them, so you can often just copy and paste from that directory. Let's show an example:
If you need a custom url
function, go to the functions directory and copy/paste one of those files (e.g., pl_kint.function.php
) into a new file named pl_url.function.php
in the same directory (the pl_
namespace is important - this tells Drupal to ignore this file). In the code, replace any relevant pieces with your own like so:
<?php
/**
* @file
* Add "url" function for Pattern Lab.
*/
$function = new Twig_SimpleFunction('url', function ($string) {
return $string;
});
Notice this isn't doing anything but returning a string as an argument, which for most cases will be all you need. Save that file, rerun the yarn start
command and voila! Now Pattern Lab will recognize that function and no more error!
If you need to write a more advanced or custom extension, here is a good starting place for doing so.
- Home
- Basics
- Examples
- Environment-specific or Special Instructions
- Acknowledgements
- To-do
- Contribute to this Wiki!