PHPackages                             nystudio107/craft-twig-sandbox - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. nystudio107/craft-twig-sandbox

ActiveLibrary[Templating &amp; Views](/categories/templating)

nystudio107/craft-twig-sandbox
==============================

Allows you to easily create a sandboxed Twig environment where you can control what tags, filters, functions, and object methods/properties are allowed

5.0.5(9mo ago)5373.5k↓11.9%3MITPHPCI passing

Since Jul 3Pushed 9mo ago4 watchersCompare

[ Source](https://github.com/nystudio107/craft-twig-sandbox)[ Packagist](https://packagist.org/packages/nystudio107/craft-twig-sandbox)[ GitHub Sponsors](https://github.com/khalwat)[ RSS](/packages/nystudio107-craft-twig-sandbox/feed)WikiDiscussions develop-v5 Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (22)Used By (3)

[![Scrutinizer Code Quality](https://camo.githubusercontent.com/9e33eb9ca3327869dc797bf028a913271d934f38cc7dc713c8f619a99bf7912b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d747769672d73616e64626f782f6261646765732f7175616c6974792d73636f72652e706e673f623d7635)](https://scrutinizer-ci.com/g/nystudio107/craft-twig-sandbox/?branch=develop) [![Code Coverage](https://camo.githubusercontent.com/3ee0804fd280f86fdce8dcd978af682c64187951019efb9dcf5fcbb3e32daea8/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d747769672d73616e64626f782f6261646765732f636f7665726167652e706e673f623d7635)](https://scrutinizer-ci.com/g/nystudio107/craft-twig-sandbox/?branch=develop) [![Build Status](https://camo.githubusercontent.com/7fb44c6154000d84a1905027c1ff381296762e3bef1ca782c1a2e333a80df67e/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d747769672d73616e64626f782f6261646765732f6275696c642e706e673f623d7635)](https://scrutinizer-ci.com/g/nystudio107/craft-twig-sandbox/build-status/develop) [![Code Intelligence Status](https://camo.githubusercontent.com/719c530ceb551e883ffd858523e6976ee9fda7547c1273afb4004d409abaa848/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e7973747564696f3130372f63726166742d747769672d73616e64626f782f6261646765732f636f64652d696e74656c6c6967656e63652e7376673f623d7635)](https://scrutinizer-ci.com/code-intelligence)

Craft Twig Sandbox
==================

[](#craft-twig-sandbox)

Allows you to easily create a sandboxed Twig environment where you can control what tags, filters, functions, and object methods/properties are allowed

Requirements
------------

[](#requirements)

Craft Twig Sandbox requires Craft CMS 5.x

Installation
------------

[](#installation)

To install Craft Twig Sandbox, follow these steps:

1. Open your terminal and go to your Craft project:

    ```
     cd /path/to/project

    ```
2. Then tell Composer to require the package:

    ```
     composer require nystudio107/craft-twig-sandbox

    ```

About Craft Twig Sandbox
------------------------

[](#about-craft-twig-sandbox)

Rather than just creating a new Twig `Environment` for the sandbox, Craft Twig Sandbox sub-classes the Craft `View` class, which has a few benefits:

- You get all of the Craft provided tags, filters, functions, objects, globals, etc. available to you if you want
- Plugin-provided tags, filters, functions, and objects are available if you want
- You get access to the familiar `.renderObjectTemplate()`, `.renderString()`, `.renderPageTemplate()` and `.renderTemplate()` methods
- All of the normal Craft events and scaffolding related to template rendering are present as well

It also implements an `ErrorHandler` that sub-classes the Craft `ErrorHandler` which is used to handle exceptions that happen when rendering Twig templates. This allows you to optionally display exceptions such as:

```
Twig\Sandbox\SecurityNotAllowedFunctionError
Function "dump" is not allowed in "__string_template__b0120324b463b0e0d2c2618b7c5ce3ba" at line 1.

```

Using Craft Twig Sandbox
------------------------

[](#using-craft-twig-sandbox)

In its simplest form, you can create a Twig Sandbox like so:

```
use nystudio107\crafttwigsandbox\web\SandboxView;

$sandboxView = new SandboxView();
```

This will create a new `SandboxView` that works just like the Craft web `View` class so you can use any of the `View` render methods for Twig templates:

```
$result = $sandboxView->renderString();
$result = $sandboxView->renderObjectTemplate();
$result = $sandboxView->renderPageTemplate();
$result = $sandboxView->renderTemplate();
```

...and they will be rendered using the default `BlacklistSecurityPolicy` so blacklisted Twig tags, filters, functions, and object methods/properties will not be allowed.

If any tags, filters, functions, or object methods/properties are used that are not allowed by the security policy, a `SecurityError` exception will be thrown.

**N.B.:** For performance reasons, you should create a `SandboxView` once, and use it throughout your application's lifecycle, rather than re-creating it every time you want to render Twig using it.

### Exception handling

[](#exception-handling)

Note that in the above example, exceptions will be thrown if the security policy is violated; so you can handle the exception yourself if you like:

```
use nystudio107\crafttwigsandbox\web\SandboxView;
use Twig\Sandbox\SecurityError;

$sandboxView = new SandboxView();
try {
    $result = $sandboxView->renderTemplate();
} catch (\Throwable $e) {
     // If this is a Twig Runtime exception, use the previous one instead
     if ($e instanceof SecurityError && ($previousException = $e->getPrevious()) !== null) {
         $e = $previousException;
     }
    // Exception handling here
}
```

Or if you want to use Craft's default web/console exception handling when rendering templates, you can do that like this:

```
use nystudio107\crafttwigsandbox\web\SandboxView;

$sandboxView = new SandboxView();
try {
    $result = $sandboxView->renderTemplate();
} catch (\Throwable $e) {
    $sandboxView->sandboxErrorHandler->handleException($e)
}
```

...and the exception with a full stack trace will be displayed in the web browser, or in the console (depending on the type of the current request).

### BlacklistSecurityPolicy

[](#blacklistsecuritypolicy)

The `BlacklistSecurityPolicy` is a `SecurityPolicy` that specifies the Twig tags, filters, functions, and object methods/properties that **are not** allowed.

It defaults to [reasonable subset of blacklisted](https://github.com/nystudio107/craft-twig-sandbox/blob/develop-v5/src/twig/BlacklistSecurityPolicy.php#L19) Twig tags, filters, and functions, but you can customize it as you see fit:

```
use nystudio107\crafttwigsandbox\twig\BlacklistSecurityPolicy;
use nystudio107\crafttwigsandbox\web\SandboxView;

$securityPolicy = new BlacklistSecurityPolicy([
   'twigTags' => ['import'],
   'twigFilters' => ['base64_decode', 'base64_encode'],
   'twigFunctions' => ['dump'],
]);
$sandboxView = new SandboxView(['securityPolicy' => $securityPolicy]);
$result = $sandboxView->renderString("{{ dump() }}", []);
```

You can also control what object methods and properties are allowed to be accessed. By default, the `BlacklistSecurityPolicy` does not restrict access to any object methods or properties.

For example, if you didn't want people to be able to access the `password` property of the `DbConfig` object via:

```
{{ craft.app.config.db.password }}
```

or

```
{{ craft.app.getConfig().getDb().password }}
```

...you would do:

```
use craft\config\DbConfig;
use nystudio107\crafttwigsandbox\twig\BlacklistSecurityPolicy;
use nystudio107\crafttwigsandbox\web\SandboxView;

$securityPolicy = new BlacklistSecurityPolicy([
   'twigProperties' => [
       DbConfig::class => ['password']
   ],
   'twigMethods' => [
       DbConfig::class => ['getPassword']
   ],
]);
$sandboxView = new SandboxView(['securityPolicy' => $securityPolicy]);
$result = $sandboxView->renderString("{{ craft.app.config.db.password }}", []);
```

If you don't want any properties or methods to be able to be accessed on a given object, you can pass in a `*` wildcard:

```
   'twigProperties' => [
       DbConfig::class => '*'
   ],
   'twigMethods' => [
       DbConfig::class => '*'
   ],
```

### WhitelistSecurityPolicy

[](#whitelistsecuritypolicy)

The `WhitelistSecurityPolicy` is a `SecurityPolicy` that specifies the Twig tags, filters, functions, and object methods/properties that **are** allowed.

It defaults to [reasonable subset of whitelisted](https://github.com/nystudio107/craft-twig-sandbox/blob/develop-v5/src/twig/WhitelistSecurityPolicy.php#L19) Twig tags, filters, functions, and object methods/properties, but you can customize it as you see fit:

```
use nystudio107\crafttwigsandbox\twig\WhitelistSecurityPolicy;
use nystudio107\crafttwigsandbox\web\SandboxView;

$securityPolicy = new WhitelistSecurityPolicy([
   'twigTags' => ['for', 'if'],
   'twigFilters' => ['replace', 'sort'],
   'twigFunctions' => ['date', 'random'],
]);
$sandboxView = new SandboxView(['securityPolicy' => $securityPolicy]);
$result = $sandboxView->renderString("{{ dump() }}", []);
```

You can also control what object methods and properties are allowed to be accessed. By default, the `WhitelistSecurityPolicy` restricts access to all object methods or properties.

That means you must explicitly specify each object property or method.

For example, if you wanted to grant access to:

```
{{ craft.app.config.general.devMode }}
```

or

```
{{ craft.app.getConfig().getGeneral().getDevMode() }}
```

...you would do:

```
use craft\config\GeneralConfig;
use craft\services\Config;
use craft\web\Application;
use craft\web\twig\variables\CraftVariable;
use nystudio107\crafttwigsandbox\twig\WhitelistSecurityPolicy;
use nystudio107\crafttwigsandbox\web\SandboxView;

$securityPolicy = new WhitelistSecurityPolicy([
   'twigProperties' => [
       CraftVariable::class => ['app'],
       Application::class => ['config'],
       Config::class => ['general'],
       GeneralConfig::class => ['devMode'],
   ]
   'twigMethods' => [
       Application::class => ['getConfig'],
       Config::class => ['getGeneral'],
   ],
]);
$sandboxView = new SandboxView(['securityPolicy' => $securityPolicy]);
$result = $sandboxView->renderString("{{ craft.app.config.general.devMode }}", []);
```

If you want all properties or methods to be able to be accessed on a given object, you can pass in a `*` wildcard:

```
   'twigProperties' => [
       DbConfig::class => '*'
   ],
   'twigMethods' => [
       DbConfig::class => '*'
   ],
```

### SecurityPolicy from a config file

[](#securitypolicy-from-a-config-file)

Often you'll want to provide a sane Twig sandbox, but also allow your users to add or remove from the policy as they see fit.

To make this easy to do, there is a `SecurityPolicy::createFromFile()` helper method to create a sandbox security policy from a config file:

```
    public static function createFromFile(string $filePath, ?string $alias = null): BaseSecurityPolicy
```

You pass it in a `$filePath`, and it will look for a file of that name (with `.php` added to the end of it) in the `craft/config/` directory. If no file is found, it will then also try to resolve the optional `$alias` and look for the file in that directory.

If the file still is not found, it will return a default `BlacklistSecurityPolicy`.

The config file is a standard [Yii2 Object Configuration file](https://www.yiiframework.com/doc/guide/2.0/en/concept-configurations).

Example files you can copy &amp; rename exists in the `craft-twig-standbox` codebase in `src/config/`, as `blacklist-sandbox.php` and `whitelist-sandbox-php`.

These are the default files that are used to create the respective security policies when you allocate a new `BlacklistSecurityPolicy` or `WhitelistSecurityPolicy`, and pass in no object configuration.

So for a practical example, the author of the SEOmatic plugin would copy the `config/blacklist-sandbox.php` file to that plugin's `src/` directory as `seomatic-sandbox.php`, and put in any customizations that they might want there.

Then they could direct their users to copy the `seomatic-sandbox.php` file to their `craft/config/` directory if they wanted to make any customizations to it.

Then to create the sandbox view in the plugin, they would do:

```
use nystudio107\crafttwigsandbox\helpers\SecurityPolicy;

$securityPolicy = SecurityPolicy::createFromFile('seomatic-sandbox', '@nystudio107/seomatic');
$sandboxView = new SandboxView(['securityPolicy' => $securityPolicy]);
```

This will cause it to create the sandbox from the `seomatic-sandbox.php` file in the `craft/config/` directory (if it exists), and if it does not exist, it will load the config file from the `seomatic-sandbox.php` in the `@nystudio107/seomatic` directory (which points to the plugin's source).

Craft automatically creates a namespaced alias for each plugin.

### Adding TwigExtensions

[](#adding-twigextensions)

By default, the Twig `SandboxView` will only have the Twig extensions in it that Craft itself registers. Any Twig extensions that are added by plugins or modules will not be present.

This is because there is no "Register Twig Extensions" event sent by Craft that plugins are modules can listen for, so the `SandboxView` has no way to tell each plugin or module to register their Twig extensions in the Twig `SandboxView`.

Instead, if you have Twig extensions that you want added to your Twig `SandboxView`, you can either do it manually:

```
$sandboxView = new SandboxView();
$sandboxView->registerTwigExtension(new MyTwigExtension());
```

...or you can pass in an array of class names to the constructor, and have the Twig `SandboxView` instantiate the Twig extensions for you:

```
$sandboxView = new SandboxView(['twigExtensionClasses' => [
    MyTwigExtension::class,
    AnotherTwigExtension::class,
]]);
```

### Custom SecurityPolicy

[](#custom-securitypolicy)

You can also create your own custom `SecurityPolicy` to use, it just needs to conform to the Twig [`SecurityPolicyInterface`](https://github.com/twigphp/Twig/blob/3.x/src/Sandbox/SecurityPolicyInterface.php):

```
use my\custom\SecurityPolicy;
use nystudio107\crafttwigsandbox\web\SandboxView;

$securityPolicy = new SecurityPolicy([
]);
$sandboxView = new SandboxView(['securityPolicy' => $securityPolicy]);
$result = $sandboxView->renderString("{{ dump() }}", []);
```

### Adding a SandboxView via `config/app.php`

[](#adding-a-sandboxview-via-configappphp)

If you want to make a Twig sandbox available globally in your Craft application, you can add the following to your `config/app.php`:

```
use craft\config\DbConfig;
use nystudio107\crafttwigsandbox\twig\BlacklistSecurityPolicy;
use nystudio107\crafttwigsandbox\web\SandboxView;

return [
    // ...
    'components' => [
        'sandboxView' => [
            'class' => SandboxView::class,
            'securityPolicy' => new BlacklistSecurityPolicy([
                'twigProperties' => [
                    DbConfig::class => '*'
                ],
                'twigMethods' => [
                    DbConfig::class => '*'
                ],
            ]),
        ],
    ],
];
```

This will create a globally available component that you can use via:

```
Craft::$app->sandboxView->renderString('{% set password = craft.app.getConfig().getDb().password("") %}');
```

You can even globally replace the default Craft `view` with a `SandboxView` if you want:

```
return [
    // ...
    'components' => [
        'view' => [
            'class' => SandboxView::class,
            'securityPolicy' => new BlacklistSecurityPolicy([
                'twigProperties' => [
                    DbConfig::class => '*'
                ],
                'twigMethods' => [
                    DbConfig::class => '*'
                ],
            ]),
        ],
    ],
];
```

Craft Twig Sandbox Roadmap
--------------------------

[](#craft-twig-sandbox-roadmap)

Brought to you by [nystudio107](https://nystudio107.com/)

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance58

Moderate activity, may be stable

Popularity41

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~23 days

Recently: every ~0 days

Total

19

Last Release

274d ago

Major Versions

4.0.3 → 5.0.32025-06-08

3.0.4 → 4.0.42025-06-10

4.0.4 → 5.0.42025-06-10

v3.x-dev → 4.0.52025-08-18

v4.x-dev → v5.x-dev2025-08-18

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7570798?v=4)[Andrew Welch](/maintainers/khalwat)[@khalwat](https://github.com/khalwat)

---

Top Contributors

[![khalwat](https://avatars.githubusercontent.com/u/7570798?v=4)](https://github.com/khalwat "khalwat (113 commits)")[![bencroker](https://avatars.githubusercontent.com/u/57572400?v=4)](https://github.com/bencroker "bencroker (3 commits)")[![lindseydiloreto](https://avatars.githubusercontent.com/u/5309692?v=4)](https://github.com/lindseydiloreto "lindseydiloreto (1 commits)")

---

Tags

craftcmssandboxsecuritytwigtwigsecuritycmsCraftcraftcmssandbox

### Embed Badge

![Health badge](/badges/nystudio107-craft-twig-sandbox/health.svg)

```
[![Health](https://phpackages.com/badges/nystudio107-craft-twig-sandbox/health.svg)](https://phpackages.com/packages/nystudio107-craft-twig-sandbox)
```

###  Alternatives

[nystudio107/craft-autocomplete

Provides Twig template IDE autocomplete of Craft CMS &amp; plugin variables

44204.4k13](/packages/nystudio107-craft-autocomplete)[wbrowar/guide

A CMS Guide for Craft CMS.

6154.5k1](/packages/wbrowar-guide)[jalendport/craft-preparse

A fieldtype that parses Twig when an element is saved and saves the result as plain text.

1086.4k](/packages/jalendport-craft-preparse)[viget/craft-classnames

Classnames plugin for Craft CMS

1115.5k1](/packages/viget-craft-classnames)[clearbold/fixmealink

Fix Me a Link is a Craft plugin with link utility functions.

151.4k](/packages/clearbold-fixmealink)[verbb/footnotes

Adds a footnotes feature to CKEditor fields and Twig templates.

213.3k](/packages/verbb-footnotes)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
