0

I have a controller that renders page elements. I have a php variable of type png image. What is the proper way to render it?

My code:

public function buildPage() {

    $page = [];

    $block_manager = \Drupal::service('plugin.manager.block');
    $config = [];
    $plugin_block = $block_manager->createInstance('my_custom_block', $config);


    $page['element_one'] = $plugin_block->build();

    $page['element_two'] = array(
      '#type' => 'markup',
      '#markup' => $this->t('This is the second page element'),
    );

    //How to render this on a third page element?
    $image = 'test.png'

    return $page;
  }

Thank you

1 Answer 1

0

You can add the element using the image theme hook:

$page['element_three'] = [
  '#theme' => 'image',
  '#uri' => $image_path,
  '#alt' => $title,
  '#title' => $title,
  '#width' => $width,
  '#height' => $height,
];
4
  • Thank you Jaypan. This image comes from google chart api as an image. Should I save it first to my public or privete files first right? Thank you,
    – Alvaro dM
    May 5, 2020 at 15:32
  • Depends on the project requirements. Too much variability to give a generic response to that question.
    – Jaypan
    May 5, 2020 at 15:59
  • So.. It is possible to render a php image variable directly with the image theme hook without an specific url? Thank you,
    – Alvaro dM
    May 5, 2020 at 17:10
  • Finally I noticed that doing the request with \Drupal::httpClient() returned a psr7 object. So i tried to directly use the google chart api url as the #uri array setting. Thank you very much.
    – Alvaro dM
    May 5, 2020 at 18:16

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.