PatternLab: Linking to Patterns

Linking patterns allows us to give our users a real feeling for how the website is going to work, on real devices, which things like InVision can never do. Here's some simple approaches.

When using PatternLab, you can link to a pattern by creating a variable such as {{ url }}. Then in your corresponding JSON or YML file, you can setting this variable equal to something like

url: link.pages-contact

or

url: link.pages-homepage.

We often use this when creating menu items, since in Drupal our menu items template looks for two parts to the menu link: title and url, something like this:

 menu: 
  items: 
    item_1:
       title: 'About Us' 
       url: link.sample-pages-basic-page 
    item_2: 
      title: 'Contact Us' 
      url: link.sample-pages-basic-page-contact-us 

This works great when working with a template that has a specific variable for the URL, such as the link to a node in node.html.twig, so we can link the title in our teaser template in PL to our sample blog pattern, for example.

But if we have a link field, such as a Call to Action in a paragraph bundle we might have something like this in our pattern:

<div class="cta__link">{{ cta_link }}</div>

and this in our corresponding YML file:

cta_link: 'Click Me!' 

We don't have PL paths in those links, because if we swap `#` for a `link.sample-pages-basic-page` it'll just render that as a string. And we don't want to break the variable into two parts, because in the Drupal template, we want to be able to {% set cta_link = content.field_cta %} and let Drupal do all its render magic.

The solution? Don't break up variable into two parts, concatenate what you want in YML instead to allow us to link to specific patterns:

cta_link: 
  join(): - '<a href="'
    - link.sample-pages-basic-page-with-quote
    - '">See Ways to Help</a>'

Now, the first part will render as a string, the second as a variable to the pattern you want to link to, and the third part as a string.

We could also create a link pattern, and do something like this:

cta_link: 
  include(): 
    pattern: 'organisms-link' 
    with: 
      url: 'link.sample-page-homepage' 

I don't, because, in general, I don't like patterns to depend on other patterns. This is simply so I can drag and drop them from project to project without any friction. Each component has everything it needs contained within it. It also means in case of something like a link field, we can let Drupal do as much of the heavy lifting as possible.

Filed Under:

  1. PatternLab
  2. Frontend Development
  3. Drupal Planet
  4. Web Design
  5. Design in Browser