Twig Tips & Tricks - HL Vanilla Community
<main> <article class="userContent"> <p>Here are a few simple tips to get the most out of Twig views.</p><h2 data-id="handling-null-or-undefined-values">Handling null or undefined values</h2><p>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. <em>In production these will downgraded to warnings and notices however.</em></p><p>If you find yourself running into one of these errors, there are one of two paths to take.</p><h3 data-id="check-for-typos-or-bugs">Check for Typos or Bugs</h3><ul><li>Make sure you are accessing the variable correctly.</li><li>Make sure the template is actually receiving the values you think it is.</li></ul><p>An easy way to the current variables in your template is to temporarily add the following to your view.</p><pre class="code codeBlock" spellcheck="false" tabindex="0">// Rest of view {{ dump() }} // Rest of View </pre><p>This will print out all the variables it is currently receiving. <strong><em>Don't forget to remove it afterwards!</em></strong></p><h3 data-id="the-value-could-potentially-not-be-defined">The Value could potentially not be defined</h3><p>The easiest way out of this is to use the <code class="code codeInline" spellcheck="false" tabindex="0">|default</code> modifier.</p><pre class="code codeBlock" spellcheck="false" tabindex="0">// "User" might not be defined. {{ record.insertUser.name|default("Unknown User") }} </pre><h2 data-id="handling-already-formatted-html">Handling already formatted HTML</h2><p>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.</p><p>Some examples of this would be:</p><ul><li>Firing events that generate HTML.</li><li>User content that is rendered by the <code class="code codeInline" spellcheck="false" tabindex="0">FormatService</code>.</li><li>Boundaries between old PHP views & new twig templates during a refactoring period.</li></ul><p>This can cause content to become double encoded or to encode content that should actually be RAW HTML.</p><p>There are 2 methods to deal with this:</p><ol><li>Use the twig <code class="code codeInline" spellcheck="false" tabindex="0">raw</code> filter.</li><li>Wrap the HTML data in <code class="code codeInline" spellcheck="false" tabindex="0">new \Twig\Markup($html, 'utf-8')</code>.</li></ol><p><strong><em>Always prefer using method 2! </em></strong>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.</p><p>It is always preferable to mark some <em>data</em> as safe where to the data is passed, than to mark it as safe when in the view, where it's origins are unknown.</p> </article> </main>