I have a custom block type with two different fields. What I am trying to accomplish is, to hide the first field if the second is not empty.

That seems like something that could be done in template_preprocess, but where would I put it and what would be my template?


3 Answers 3


you can utilize twig's if/else condition:

{% if field_NAME_OF_YOUR_SECOND_FIELD.0 == false %}
    {{ field_NAME_OF_YOUR_FIRST_FIELD.0 }}
{% endif %}

check this for extracting the values of different fields


Preprocessing the block_content template was considered undesireable, and they suppressed the functionality. There is a module on github that provides this functionality, but since it lacks composer support, you might just copy it into your project.

All that said, you should find that template_preprocess_block allows access to what you want, and this might work:

function MYTHEME_preprocess_block(&$variables) {


Custom block type is available in $variables['content']['body']['#bundle'] Refer the below sample function

function mytheme_preprocess_block(&$variables) {
  if ($variables['content']['body']['#bundle'] == 'my_block_type') {
    // Do whatever specific to the block type.

Adding a bit more information as per @berliner commented

$variables['content']['#block_content'] //will hold the content entity

$variables['content']['#block_content']->id() //will give you the content id, ie. the custom block content id

In order to alter any field you could apply logic inside the conditional statement

Ref. belwo code where the values are assigned to a drupalSettings js variable.

function mytheme_preprocess_block(&$variables) {
        if($variables['content']['body']['#bundle'] == 'my_custom_block_type')


I would prefer to log drupalSettings.full_content to a javascript console, which would give a bigger picture of the whole variables and manipulate accordingly Ref: JS function

(function($, Drupal, drupalSettings) {

Drupal.behaviors.myCustomJSFunction = {
    attach: function (context, settings) {
     })(jQuery, Drupal, drupalSettings, window.Cookies);
  • This could be improved, as it doesn't seem to fully address the original problem of this question. It shows how to identify the block, but not how to modify it.
    – berliner
    Mar 22, 2022 at 9:07

Your Answer

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

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