8 – How to hide an empty field if my custom field formatter deletes all the elements?

I have a custom field formatter (in Drupal 8) that displays a list of taxonomy terms on a node. Some terms are not supposed to be displayed. The field formatter removes them from the list of items.

Sometimes all the elements are deleted – but the HTML elements that surround the field are always rendered. How to completely hide the field when all elements are deleted?

EDIT FOR CLARITY:

I have a field with the machine name field_tags which is an entity reference to several taxonomy terms.

To make this field, I wrote a custom trainer as a field trainer plug-in in a custom module. The code is stored at the standard location in mymodule / src / Plugin / Field / FieldFormatter / TermListFormatter.php.

My class extends EntityReferenceFormatterBase.

In my class, my viewElements () method deletes some elements and sometimes returns an empty array if no element needs to be rendered.

        public function viewElements (FieldItemListInterface $ items, $ langcode) {
$ elements = [];

// Loop through each of the terms in this field.
foreach ($ this-> getEntitiesToView ($ items, $ langcode) as $ delta => $ entity) {
$ label = $ entity-> label ();

// ONLY displays the taxonomy terms beginning with "Test".
if (mb_substr ($ label, 0, 5) === & # 39;)
$ options = [
          'query' => [
            'tags' => [$entity->id()],
],
];

// Terminates the terms as links to / test? tags[]= {tid}
$ elements[$delta] = [
          '#type' => 'link',
          '#title' => $label,
          '#url' => Url::fromRoute('view.test.page_1'),
          '#options' => $options,
        ];

if (! empty ($ items[$delta]-> _ attributes))) {
$ elements[$delta]['#options']    + =['attributes'=>['Attributes'=>['attributs'=>['attributes'=>[]];
$ elements[$delta]['#options']['attributes']    + = $ items[$delta]-> _ attributes;
// Removes the field element attributes as they were included in the
// the formatter is generated and should not be rendered in the field template.
unset ($ items[$delta]-> _ attributes;
}

$ elements[$delta]['#cache']['tags']    = $ entity-> getCacheTags ();
}
}

// This will be an empty array if there are no terms beginning with "Test"
returns $ elements;
}

When all terms are deleted, the field wrapper elements are always displayed as follows:


  

How can I prevent these items from appearing when there are no terms to display?