Who this is for. The technical lead of a Twig site, and whoever reviews its templates and the template code kept in its admin. Afterwards you know what the engine leaves to the reviewer, and what to check for it.
No sandbox
Twig offers an optional sandbox: a policy listing the tags, filters, functions, methods and properties a template may use. The platform does not enable it, so there is no such list on a Twig site. A template may use every tag, filter and function installed (What the platform adds to Twig) and call the public methods of the objects it is given.
Compared with Smarty's policy:
| Smarty | Twig | |
|---|---|---|
| PHP functions | Only the 98 on the policy's list | None directly: Twig templates use Twig's own filters and functions |
| Engine features | All of Smarty's tags and modifiers | All of Twig's tags, filters and functions |
| Methods on records | Only those on the record's response model list | The same list: the platform enforces it before either engine sees the record |
| A refused or unknown call | The template fails to compile, naming the call | An unknown filter or function fails to compile; a method a record refuses prints nothing |
| Files | Only from the template folders | Only from the template folders |
So the safety net Smarty's list gives against an expression nobody reviewed is absent in Twig. For templates in the repository that changes little: they go through version control and review either way. It matters for template code that people other than developers can edit: the code in jobs, discount conditions, shipping methods and the search facets template, and on a Twig site the subject and body of Mailer emails (Rendering a template from a string). Decide who may edit those records, rather than relying on the engine to decide for you.
Reviewing Twig code that non-developers can edit
- Who can edit it? Restrict editing of jobs, discounts, shipping methods and search settings to the people you would let commit to the repository.
- Who last changed it, and why? Read the record's history before trusting the code.
- What does it touch? List the objects it uses and check that it only reads them, unless writing is its purpose.
- Is every output encoded for its destination?
|json_encodeinto JSON,|einto HTML,|e('url')into a URL. - Does it hold anything secret? Keys and passwords do not belong in template code.
- What happens when it fails? A failed discount condition does not apply and a failed shipping method offers no rates; both log the error, so check there rather than waiting on the visitor to report it.
No autoescaping
Stock Twig escapes every {{ }} in an HTML template unless told otherwise. The platform switches that off, so {{ value }} prints the value exactly, as Smarty does. You choose the escaping for each output: