0

I'm creating a Drupal 8 theme. I have overriden the menu.html.twig... and I need to add an image to the first menu item.

In the page.html.twig I have used {{ base_path ~ directory }} to get the url of image like this:

<img class="logo_inder" src="{{ base_path ~ directory }}/img/logo-inder.png" />

But I'm trying to insert an image in themes/(my_theme)/templates/menu.html.twig like this:

<img src="{{ base_path ~ directory }}/img/inicio-icono.png" />

But is in this file, I can't print these variables:

{{ directory }}
{{ base_path }}

or

{{ base_path ~ directory }}

How can I print the base URL for use in my image?

5

You can expose the base_path variable to all you templates by implementing hook_preprocess() in your theme .theme file.

e.g.

/**
 * Implements hook_preprocess().
 */
function mytheme_preprocess(array &$variables, $hook) {
  $variables['base_path'] = base_path();
}

where mytheme is the machine name of your theme.

You can use {{ active_theme_path() }} to get the path to the active theme.

  • Thank you... the active_theme_path() worked perfectly to print yhe path of the active theme But the base_path didnt work... it is not printing anything... I rebuilded cache .... Do you know why drupal doesnt have this "base_path" variable by default in all the *.html.twig files under the template folder in themes? it should be a nice improvement... how can we suggest that? – Victor Hugo Arango A. Aug 24 '16 at 22:11
  • To suggest new things or report bugs just open a new issue on drupal.org for the Drupal project. The preprocess hook works, are you sure you named it correctly after your theme? – zerolab Aug 25 '16 at 8:26
  • I'm trying to print it using the tag {{ base_path }} but is not working... that could be the mistake? I also tried to implement it in the function. "mytheme_preprocess_menu(&$variables, $hook, $info) " but still not working – Victor Hugo Arango A. Aug 25 '16 at 19:08
  • I'm afraid I cannot help without more background information. if your theme is called my_theme then the function should be my_theme_preprocess_menu() and for my example my_theme_preprocess(). We use this method to expose the variable everywhere and it works – zerolab Aug 26 '16 at 11:59
  • thanks for your help... I have a clue about my problem... If I use the base_path before the macro... it prints the value of the base path... {{ base_path }} {% macro menu_links(items, attributes, menu_level, base_path) %} but if I print it after the macro... it doesnt print anything! {% macro menu_links(items, attributes, menu_level, base_path) %} {{ base_path }} – Victor Hugo Arango A. Sep 13 '16 at 19:13

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.