Search cookbook and controllers

Hello!

I’m slowly building my website and trying to better understand Kirby.

I’ve added a search on my website following the Search recipe on the cookbook but encountered some issue and I would like to understand if my solution was the proper one and why.

I’ve put the form in my header snippet but otherwise I’ve followed the cookbook. I could not make the form work (except on the search page). I guessed it was because the $query variable was not shared with the other templates.

So I’ve added the variable in my site controller and it’s working perfectly now. Was this the right thing to do or should I have done things differently?

I don’t really understand why it is now working or why I only need to add the $query in the site controller and not the other.

I have a:

  • site controller
  • note controller
  • search controller.
In the site controller:
<?php

return function ($page, $pages, $site, $kirby) {
    
  # Fetch and store the content for the title tag and the meta description
  $titleTag = Str::unhtml($page->title()) . " | " . $site->title();
  #  Stylesheets can be included using the `css()` helper. Kirby also provides the `js()` helper to include script file.
  #More Kirby helpers: https://getkirby.com/docs/reference/templates/helpers
  $links = css(['assets/css/index.css', '@auto']);
  $metaDescription = $page->text()->excerpt(120);
  
  $query   = get('q');
  # Return an array containing the data that we want to pass to the template
  return compact('titleTag' , 'links', 'metaDescription', 'query');

};

In the search controller
<?php

return function ($page, $pages, $site, $kirby) {

  # Grab the data from the default controller
  $shared = $kirby->controller('site' , compact('page', 'pages', 'site', 'kirby'));
  # Store the content for the different title tag
  $query   = get('q');
  $results = $site->index()->listed()->search($query, 'title|text');
  $results = $results->paginate(20);
  $titleTag = Str::unhtml($page->title()) . " $query  | " . $site->title();
  $links = css(['assets/css/index.css', 'assets/css/templates/notes.css', '@auto']);


  return [
    'query'      => $query,
    'results'    => $results,
    'pagination' => $results->pagination(),
    'titleTag' => $titleTag,
    'links' => $links
  ];

};

Thank you for time and help.

Defining the variable in the site controller doesn’t make sense, because all other controllers overwrite the site controller for the given page type.

I’d recommend you replace html($query) with html(get('q')) or simply leave the value empty.

1 Like

Thank you! I was feeling that the solution was weird and it was not making any sense for me because I did understand that the other controllers would overwrite the site controller and that I would need to define the variable in each controller.

I’ve replace html($query) by html(get('q')) in my snippet :slight_smile:

Thanks again!