7

I'm creating a custom theme. Under my theme's folder, there is an images folder where I've put some pictures. I want to use these images in my various template (.tpl.php) files using HTML <img> tag... but the problem is how do i get correct path for these images (the src attribute)?

I've searched for a while but didn't get any solutions. Please help.

EDIT: I'm using nice urls (http://mydrupalsite.com/a/b/c/d) - type URLs. So, if the image src begins with / (or any relative path) it would break.

14

I think these functions could be useful in your templates:

print base_path() . path_to_theme();

path_to_theme() Return the path to the current themed element. base_path() The base path of the Drupal installation.

for example, I have an image called bg-bar.png inside images directory in my template directory called garland. then I can use base_path() and path_to_theme() to get the path to the image, for example inside node.tpl.php:

print '<img src="'.base_path() . path_to_theme() .'/images/bg-bar.png">';

Update: if you want to use the current domain, you can use global $base_root:

  $address = ''.base_path() . path_to_theme() .'/images/bg-bar.png';
  global $base_root;
  echo '<img src="' . $base_root . $address . '">';

I hope information be useful.

  • I've tried all these. Problem is, base_path() returns '/' - which does not help when I'm using nice urls (i.e. mysite.com/a/b/c) - in this case image source becomes '/path-to-theme/...../image.png' - which does not work. I need to use http:// instead of / in image source I guess. – Shafiul Oct 15 '11 at 19:20
  • I updated my answer with information related with http://. – cigotete Oct 15 '11 at 19:47
  • If you are using 'nice urls' I guess that these urls are controlled by a rewrite process, so I think that you can add exeptions. For example, review if from .htaccess file you can control this rewrite process, and add the respective condition with RewriteCond to exclude images. – cigotete Oct 15 '11 at 20:15
  • Thank you! I have been looking all over for a solution for this problem! – user1015214 Jan 22 '13 at 4:03
0

Since my image was in a conditional block, the above syntax posed some problems and the following worked for me. However, I am not sure if it is advisable from a maintenance perspective:

src='<?php print base_path().path_to_theme().'/images/iphone.png' ?>'

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.