Sep 7, 2014

url() function in Twig templates

As of Drupal 8 alpha 14, several relative links that had been hard-coded in Twig templates were no longer working.

<li>Add the account ID to the 
<a href="/admin/config/system/optimizely/settings">
Account Info</a> settings page</li>

The url constructed by the theming system did not include the root of my development site, which is opti. Instead, it would come out as


Dropping the leading slash character in the href also produced an incorrect result. Here, add_update is the last part of the path for the page that is rendered using the template.


After some poking around, I found the Twig url() function, which does the trick.

<li>Add the account ID to the 
<a href="{{ url('optimizely.settings') }}">
Account Info</a> settings page</li>

This produces the desired url, which is


But note that the parameter to url() is the name of a route, not a path. In the optimizely.routing.yml file, the route is defined as

    path: /admin/config/system/optimizely/settings
      _form: \Drupal\optimizely\AccountSettingsForm
      _title: Optimizely
      _permission: administer optimizely

The path() and the l() functions might also work, but I haven't tried them. See the source articles.


Creating and Using Templates

Create best practices about use of the l() function and the url() function in templates

No comments:

Post a Comment