0

i created a custom block where i can upload an image. i overwrite the custom block with a template:

   <div{{ attributes }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
   <div{{ content_attributes.addClass( 'content') }}>

      <div class="row">
        <div class="col-md-12">

          {{content.field_parallax_bilder }}  <----- (1)

          <div class="parallax-window" data-parallax="scroll" data-image-src="(2)">  <----- (2)

          </div>
        </div>
      </div>
      </div>

  {% endblock %}
</div>

i want to get the path of the image (1) and include it in my data-image-src parameter (2). is there an easier way then write a block_preprocess?

1

You'll have to set a $src var from the corresponding preprocess hook.

function myModuleOrTheme_preprocess_block(&$variables){

if(isset($variables['elements']['content']['field_parralaxBgImage']))
//or any other way to test if you are in the right block

   //Get the Image id : 
   $imgListItems = $variables['elements']['content']['field_testimages']['#items'];
   $imgId = $imgListItems->getValue()[0]['target_id']; 
   //load the entity :
   $image = \Drupal\file\Entity\File::load($imageId);

  // now you can simply return the original image's url : 
  $variables['parralaxBgSrc'] = image->url();

  //or return a styled image's url (croped or resized) with a image style configured in the BO
  $imageStyle = \Drupal\image\Entity\ImageStyle::load('imageStyle_id');
  $variables['parralaxBgSrc'] = $imageStyle->buildUrl($image->getFileUri());

}

After that, you'll be able to use it in your twig tpl :

 <div class="parallax-window" data-parallax="scroll" data-image-src="{{$parralaxBgSrc}}"> 

(Dont forgot to flush your cache after adding the hook)

Et voila! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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