In my Drupal 8 site, I am developing a custom block in my module custom, with some text and some images. I created a template, and everything works fine. Now I need to add some images for my custom block, and I don't know how to pass the base URL to call those images.

In Drupal 7 I used the following code.

function bloques_block_view($delta = '') {
    $block = array();

    $ruta = $GLOBALS['base_url'] . '/' . drupal_get_path("module", "mymodule");
    $link = $GLOBALS['base_url'] ;   

  switch ($delta) {

    case 'footer':
      $block['subject'] = '';
      $block['content'] = leer_template('footer.tpl', array('%ruta%' => $ruta, '%link%' => $link));
  return $block;

Everything works well, but in Drupal 8 it is a little different. The problem comes with build().

    public function build() {
    $ruta = 'holamundo',        
    return array(
        '#theme' => 'mymodule',
        '#title' => 'my title ',
        '#ruta' => '<p>' . $ruta . '</p>'


Just the title works in the template file; $ruta is not working.

  <h2>My Custom Block {{ title }}-{{ ruta }}</h2>

I don't know if this is the correct way to declare the base URL (just like I did in Drupal 7).

  $ruta = $GLOBALS['base_url'] . '/' . drupal_get_path("module", "bloques");
  • Yes declaring base_url is correct and the same above code is working fine. Can you once try by removing <p> tag and also check declared "variables" in hook_theme for ruta.
    – Ajay Reddy
    Nov 16, 2016 at 7:39

1 Answer 1


You can try template_preprocess_block(&$variables). There is a global $base_url variable. Create variable for block template:

function your_module_preprocess_block(&$variables){
  global $base_url;
  $variables['base_url'] = $base_url;


Now you can use {{base_url}} in twig template of your block.

  • it doesnt work for me. i put the function in the block.php for my module.module and try to call the {{base_url}} in my twig file. But it doesnt work.
    – ValRob
    Nov 17, 2016 at 21:18
  • You have to put this function in your module_name.module file and not in block.php. After that this variable {{base_url}} should be accessible in all block templates.
    – Andrew Nim
    Nov 21, 2016 at 11:25
  • And the cache have to be cleared after adding this function.
    – Andrew Nim
    Nov 21, 2016 at 11:29
  • Thank you, if it works for you please mark it as right answer.
    – Andrew Nim
    Nov 28, 2016 at 20:45

Your Answer

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

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