Exercise 5

Building the Hero Image pattern

Image Data

Let's start by building the data that will populate the image pattern. This data is provided in .yml format.

  1. Inside src/components/ create a new folder called image
  2. Inside the src/components/image folder create an assets folder, and add a placeholder image. For this exercise, add an image that's 1920px wide by 1280px tall.
  3. Inside the image folder, create a new file called image.ui_patterns.yml
  4. Copy the snippet below inside image.ui_patterns.yml (indentation is important)
image:
  label: Image
  description: A simple image pattern
  fields:
    image:
      type: render
      label: Image
      description: Hero image
      preview:
        theme: image
        uri: /themes/custom/nashville/src/components/image/assets/image.jpg
        width: 960
        attributes: {alt: "Surfing person"}
  libraries:
    - image:
        css:
          component:
            image.css: {}

Note: be sure to update the image.jpg file name above with the filename of the image you added to the src/components/assets folder.

Let's take a moment to describe each of the pieces involved in the snippet above for better understanding.

image: This is the pattern name and ID. This is required.

label: Normally the name of the pattern for pattern overview purposes. This is required.

description: A description for the pattern. Optional.

fields: Hash defining of the pattern fields. Each field must have the following properties defined below.

type: Field type, can be text, numeric, etc. at the moment only used for documentation purposes.

label: Field label, used on pattern overview page.

description: Field description, used on pattern overview page.

preview: Preview content, used on pattern overview page. It can be either a string or a Drupal render array, in which case we can use keys like type: processed_textor theme: image.

NOTE: Depending on the field type, their properties will vary.

Image Markup

Now that the data source for the image pattern is ready, we can create the markup which will print the image to the screen. The markup for a pattern is written in combination of HTML and Twig. This makes creating patterns extremely efficient and powerful as twig offers so many advantages over plain html.

  1. Inside the image directory create a new file called pattern-image.html.twig
  2. Paste the snippet below into the new file
{{ image }}

Image Styles

image.css

img {
  display: block;
  max-width: 100%;
  height: auto;
}

results matching ""

    No results matching ""