2

I would like to customize the output of each search result item printed on the search result page. Right now it automatically prints a portion of the content of each item, but I'd like more control. I would like to specify what fields to display in the search result. For example I'd like to output field_image followed by field_mytextfield. Rather than whatever Drupal is doing to output the trimmed content of the result.

I'm using a template to customize the output already

{{ title_prefix }}
<div class="search-result-item">
<div class="search-title-header">
    <h4{{ title_attributes }}>
        <a href="{{ url }}">{{ title }}</a>
    </h4>
</div>
{{ title_suffix }}
{% if snippet %}
  <p{{ content_attributes }}>{{ snippet }}</p>
{% endif %}

</div>

However I don't seem to have access to what is inside snippet, and I'm not sure how to directly access the fields of the result. I'd like to use the content type's teaser as the result display but I'm not sure how to use that.

1 Answer 1

5

You can take control on which content the snippet is based by modifying the view mode "search_result". If you want to hide information from a field, then simply remove it there. But you can't change the behavior, how the snippet is composed out of this content. This is hard coded. And it will be text only with all tags removed.

If you want to provide additional elements for the search result, beside the snippet, you can do this by implementing template_preprocess_search_result in your module/theme file:

function [MODULE_NAME]_preprocess_search_result(&$variables) {
  $node = $variables['result']['node'];
  if (isset($node)) {
    $variables['teaser'] = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node,'teaser');
  }
};

And use it in twig:

{{ teaser }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.