Add cache metadata automatically
>>> [!note] Migrated issue <!-- Drupal.org comment --> <!-- Migrated from issue #3447272. --> Reported by: [erik.erskine](https://www.drupal.org/user/375884) Related to !15 >>> <h3 id="summary-problem-motivation">Problem/Motivation</h3> <p>Use of a global variable does not automatically add the necessary cache metadata to the output. You still need a preprocess function for that.</p> <!--break--><p>Example: something like <code>{{ global_variables.current_path }}&lt;code&gt; in a template is not sufficient, you still need to add the &lt;code&gt;url</code> cache context in PHP somewhere, usually in a preprocess function.</p> <h4 id="summary-steps-reproduce">Steps to reproduce</h4> <ol> <li>Ensure render caching is on. </li><li>Place a block somewhere on the page. Let's take the <em>powered by Drupal</em> block as an example, because it's trivial. </li><li>Override the template for that block. Add <code>{{ global_variables.current_path }}</code> somewhere in the template. </li><li>Visit a page. The path should be correct. The rendered output of the block will be cached. </li><li>Visit a different page. The cached block output is used, and the path is wrong. </li></ol> <h3 id="summary-proposed-resolution">Proposed resolution</h3> <p>Wrap the string value in an object that also holds the necessary cache metadata. In this example that's the <code>url</code> cache context. </p> <h3 id="summary-remaining-tasks">Remaining tasks</h3> <p>Make a patch for the <code>CurrentPath</code> plugin as a proof of concept.</p> <p>Review this approach. If it's good then path the other affected plugins.</p> <h3 id="summary-ui-changes">User interface changes</h3> <p>None.</p> <h3 id="summary-api-changes">API changes</h3> <p>Maybe. The value returned is no longer a string, although it can implement <code>\Stringable</code> and <code>__toString()</code>. That's fine for most cases, but more obscure usage like <code>{{ global_variables.path|upper }}</code> might be a problem.</p> <h3 id="summary-data-model-changes">Data model changes</h3> <p>None.</p>
issue