Here are a few simple tips to get the most out of Twig views.
Handling null or undefined values
In development, Twig will give fatal errors when accessing an undefined value. This is to make the developer more aware of the content being injected into their view, and to more easily identify typos. In production these will downgraded to warnings and notices however.
If you find yourself running into one of these errors, there are one of two paths to take.
Check for Typos or Bugs
- Make sure you are accessing the variable correctly.
- Make sure the template is actually receiving the values you think it is.
An easy way to the current variables in your template is to temporarily add the following to your view.
// Rest of view
{{ dump() }}
// Rest of View
This will print out all the variables it is currently receiving. Don't forget to remove it afterwards!
The Value could potentially not be defined
The easiest way out of this is to use the |default
modifier.
// "User" might not be defined.
{{ record.insertUser.name|default("Unknown User") }}
Handling already formatted HTML
Vanilla's twig instance is configured to automatically HTML encode untrusted characters. This is a security best practice, but can cause some errors at the boundaries of system that provide rendered output.
Some examples of this would be:
- Firing events that generate HTML.
- User content that is rendered by the
FormatService
. - Boundaries between old PHP views & new twig templates during a refactoring period.
This can cause content to become double encoded or to encode content that should actually be RAW HTML.
There are 2 methods to deal with this:
- Use the twig
raw
filter. - Wrap the HTML data in
new \Twig\Markup($html, 'utf-8')
.
Always prefer using method 2! Using method 1 may work for your particular scenario but may cause issues if in the future someone does not expect raw to be used.
It is always preferable to mark some data as safe where to the data is passed, than to mark it as safe when in the view, where it's origins are unknown.