mark.ie: PatternLab: Linking to Patterns

PatternLab: Linking to Patterns

Here’s two approaches to linking to patterns in PatternLab.

markconroy
Thu, 03/07/2019 – 11:27

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:

  1. menu:
  2.   items:
  3.   item_1:
  4.   title: 'About Us'
  5.   url: link.sample-pages-basic-page
  6.   item_2:
  7.   title: 'Contact Us'
  8.   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:

  1. {{ cta_link }}

and this in our corresponding YML file:

  1. 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:

  1. cta_link:
  2.   join():
  3. - '"'
  4. - link.sample-pages-basic-page-with-quote
  5. - '">See Ways to Help'

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:

  1. cta_link:
  2.   include():
  3.   pattern: 'organisms-link'
  4.   with:
  5.   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.