Sometimes there are unique content requirements that require content editors to insert Twig code in Craft CMS entries. However this raises several security concerns and issues. In this post I'll highlight the solution I developed for my blog.

We could just create a new field, take the raw output and throw it into the "template_from_string" Twig function. However doing that allows the execution of dangerous Twig functions. So we need to restrict what functions and filters are allowed to be used when inserting content from the CMS.

Luckily for us Twig provides something called "sandbox" mode that allows us to do just that. First you need to configure Craft to load your module if you haven't already. It should be enough to add " 'bootstrap' => ['my-module'], " to "config/app.php". If you have a default installation this line should already be present but commented out.

After that add the following code to "modules/Module.php":