I'd like to render the search block in a twig file.
please try this
/**
* Implements theme_preprocess_example_hook().
*/
function themename_preprocess_example_hook(&$variables) {
// Create a variable for the block w/ ID "example_block_id".
$block = \Drupal\block\Entity\Block::load('example_block_id');
$variables['example_block'] = \Drupal::entityTypeManager()
->getViewBuilder('block')
->view($block);
}
in your twig file
{{ example_block }}
This is a solution.
/**
* Implements hook_preprocess_page().
*
*/
function mytheme_preprocess_page(&$variables) {
$block = \Drupal\block\Entity\Block::load('mytheme_search'); // replace mytheme part with your theme name.
$variables['block_search_form'] = \Drupal::entityTypeManager()
->getViewBuilder('block')
->view($block);
}
Access it in page.html.twig file
{{ block_search_form }}
-
-
@CocoSkin replace
mytheme_search
with the name of your theme. Ex: for Bartik theme it would bebartik_search
. – No Sssweat Aug 30 '20 at 12:45 -
-
@CocoSkin it does, you're doing something wrong. Did you also replace
mytheme
in the function name? Did you add this code to your theme's .theme file? – No Sssweat Aug 31 '20 at 15:09 -
@NoSssweat yes, my theme name is "testtheme". I use "
testtheme_search
" as ID on testtheme.theme file. The hook function isfunction testtheme_preprocess_page(&$variables) { }
. – CocoSkin Sep 1 '20 at 14:09
There is a big gotcha with the search form.
The answer with the themename_search
only works if the search block is enabled or disabled and has never been removed in /admin/structure/block.
If in /admin/structure/block you re-add/place it again, the search form ID changes to formsearch
. It no longer uses the theme name! And again it only works if this block is enabled or disabled, but not when removed.
A solution that works when search block has been removed from /admin/structure/block is to use Twig Tweak and then you can place it with
{{ drupal_form('Drupal\\search\\Form\\SearchBlockForm') }}
-
Thanks @NoSssweat, this is a good workaround. I will keep looking for a solution that can print search form without a plugin. – CocoSkin Sep 2 '20 at 14:10
-
I found a solution. It can be done by using the "Including Part of Template". I use
{% include '@MYTHEME/block--search-form-block.html.twig' %}
on page.html.twig to include my customizeblock--search-form-block.html.twig
search form. – CocoSkin Sep 2 '20 at 14:26 -
I'm wrong. My solution does print the
block--search-form-block.html.twig
but the search form inside is not showing up. – CocoSkin Sep 3 '20 at 22:36
<div style="display: none;">{{ block_search_form }}</div>
– Oana Hulpoi Jun 7 '16 at 8:33