SilverStripe – Highlighting Query Text in Search Results

Normally the Page_results.ss look like this:

<ul id="SearchResults">
  <% control Results %>
  <li>
    <a href="$Link">
      <% if MenuTitle %>$MenuTitle<% else %>$Title<% end_if %>
    </a>
      <p>$Content.ContextSummary</p>
    <% end_if %>   
  </li>
  <% end_control %>
</ul>

If you want to highlight your search query, add this function to Page.php:

public function SentenceContainingQuery() {
   $query = Controller::curr()->Query;
   $content = $this->obj('Content');
   $sentences = explode( '.', $content->NoHTML());
   if ( count($sentences) ) {
      foreach($sentences as $sentence) {
         if ( strchr($sentence,$query) ) {
            return str_replace($query, "<span class='query-instance'>$query</span>", $sentence) . '.';
         }
      }
   } else {
      $sentence = $content->FirstSentence();
      return str_replace($query, "<span class='query-instance'>$query</span>", $sentence) . '.';
   }
}

In Page_results.ss add following code:

<ul id="SearchResults">
  <% control Results %>
  <li>
    <a class="searchResultHeader" href="$Link">
      <% if MenuTitle %>$MenuTitle<% else %>$Title<% end_if %>
    </a>
    <% if SentenceContainingQuery %>
      <p>$SentenceContainingQuery</p>
    <% end_if %>   
  </li>
  <% end_control %>
</ul>

And Last the css:

span.query-instance {
  font-weight: bold;
  background: #CCC;
}

Looking for quality SilverStripe Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , , | Posted under SilverStripe CMS | RSS 2.0

Author Spotlight

Teet Bergmann

Teet Bergmann

I'm a freelance web designer from Estonia. Mostly doing sites using Silverstripe, magento, prestashop, wordpress.

Leave a Reply

Your email address will not be published. Required fields are marked *


1 + = 8

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>