In my laravel app I want end users to be able to customize some email content and some page content.
So in my SaaS product they can customize the welcome email, or the page once someone joins the platform.
I am currently just providing them a few placeholders to use; ie
Hello $FirstName$,
and then in my code I simply do
$content = str_replace(['$FirstName$', '....'...
That why I know they are not going to add any php or anything. However, I need to do an if statement, and loop an object so I have hit the limits of my str_replace methods.
I can't use blade because that allows them to use <?php
so they could then mess with the app.
Twig sounds like it could be a good fit.
So;
Is there something like that?
Yes, twig supports loading of untrusted templates with the sandbox extension.
The
sandbox
extension can be used to evaluate untrusted code. Access to unsafe attributes and methods is prohibited. The sandbox security is managed by a policy instance. By default, Twig comes with one policy class:Twig_Sandbox_SecurityPolicy
. This class allows you to white-list some tags, filters, properties, and methods:$tags = array('if'); $filters = array('upper'); $methods = array( 'Article' => array('getTitle', 'getBody'), ); $properties = array( 'Article' => array('title', 'body'), ); $functions = array('range'); $policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
You would then use it like this:
{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
There is no way to execute raw PHP from twig templates by default, so your users would not be able to abuse the system too much. They could still potentially cause infinite loops, but no system that allows more than string replacement can prevent that.