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

  localhost/admin/config/system/optimizely/settings

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.

  localhost/opti/admin/config/system/optimizely/add_update/admin/config/system/optimizely/settings

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

  localhost/opti/admin/config/system/optimizely/settings

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

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


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

Sources:

Creating and Using Templates
http://symfony.com/doc/current/book/templating.html

Create best practices about use of the l() function and the url() function in templates
https://www.drupal.org/node/1812562

No comments:

Post a Comment