1

I'm doing my first site on Drupal 8 and I have a problem. I would like you to help me.

In fact I'm trying to get the articles attached images as a background for a div created in the page templates.

I wrote this code in my theme.file

function THEME_preprocess_page(&$variables, $hook) {

// Set articles attached img like background
$node = Drupal::request()->attributes->get('node');
if($node){
    if ($node->bundle() == "article") { // Content type check
        $image = file_create_url($node->field_image->entity->getFileUri()); // Creating file path from uri
        $variables['article'] = true; // Setting value true for current node is articles.
        $variables['background_img'] = $image;
    }
  }
}

and I try to get the image back with the following code in the field--node--field-image--article.html.twig template

<div class="img-ban" style="background: url({{ my_image }});"></div>

but it doesn't work.

Can someone tell me what's wrong with this code? I would really appreciate it. Thank you.

  • 1
    You defined an additional template variable background_img and try to use the variable my_image. This obviously won't work. Furthermore, you are using the page preprocess hook and try to access the variable in the field template, which also won't work. Each template has its own preprocess hooks. See api.drupal.org/api/drupal/… - You may need to replace HOOK with field. – Mario Steinitz Mar 23 at 3:29
  • You're right, you're right. I didn't pay attention to 'my_image' when I was posting my question. I had fixed it well and it didn't work. And you're right about using field instead of hook. I hadn't thought of that at all. I'm actually new, I'm trying to get used to it. GyorgosK gave me the complete answer. The subject is solved. Thank you for your help. – Worksfather Mar 23 at 21:44
3

Contrib module

What you are describing can be done easily with a contrib module. You could try background_image, bg_image_formatter, bg_img_field perhaps there are others.

Use image in node.html.twig or variant

If you MUST DO IT WITH CUSTOM CODE and you want my_image in node.html.twig or node--article.html.twig you need to prepare it in hook_preprocess_node

function THEMENAME_preprocess_node(&$variables) {
    $node = $variables["node"];
    if ($node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
      // can set more variables
    }
}

Use image in page.html.twig

If you want to include it in a div inside your page.html.twig you should use hook_preprocess_page and note that $node has to be extracted from the ROUTE

function THEMENAME_preprocess_page(&$variables) {
  // get the current node
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node->bundle() == "article" && $node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
      // can set more variables
    }
  }
}

Use image in field.html.twig or variant

I can't see the use case but if you want to use it in field.html.twig or a variant such as field--node--field-image--article.html.twig you can access it directly

{% set my_image = file_url(element['#object'].field_image.0.entity.uri.value) %}

or can set my_image using a hook_preprocess_field

function THEMENAME_preprocess_field(&$variables) {
  if($variables["element"]["#field_name"] == "field_image"){
    // get parent node
    $node = $variables['element']['#object'];
    if ($node->bundle() == "article" && $node->hasField('field_image')) {
      $variables["my_image"] = file_create_url($node->field_image->entity->getFileUri());
    }
}
  • Thank you @GiorgosK. You saved me ! I really wanted to use in a field template. And your code to include directly in field template works very well. Thank you very much. – Worksfather Mar 23 at 21:35
  • Hi @GiorgosK. I hope you're all right. I'm trying to apply the first method for node.html.twig, but it doesn't work. It says "Error: Call to a member function hasField() on null in THEME_preprocess_node()" Can you tell me what can cause this please? It had worked before though. – Worksfather Jun 3 at 1:56
  • @Worksfather, I think the $node was not assigned properly, $node = $variables["node"]; I have added this to the answer. – GiorgosK Jun 3 at 3:47
  • It works ! Thank you very much. But tell me, I would really like to learn how to code all this myself. What do you advise me to do to succeed? – Worksfather Jun 3 at 11:41
  • Glad it worked. About learning there is no one single path to learning. General overview would be to setup your development enviroment drupal.org/docs/develop/local-server-setup, setup and learn how to use the debugger (xdebug for php) with your favorite editor or IDE, read the docs, read tutorials, exercise by doing real work, ask and try to understand the answers. The debugger I believe is a step that most people overlook but it can help you understand parts of the code that no tutorials can teach you. drupal.org/docs/develop/development-tools/xdebug-debugger – GiorgosK Jun 3 at 11:57

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.