How to add an HTML attribute to a CCK image field

2019-06-04 17:23发布

I am trying to add an attribute of "id="background" to the actual image tag.

<?php print render($content['field_bg_image']); ?>

I've looked up tons of articles and they are all concerned with hook_form_alter and this is not a form. This is simply just an image field, I just need an ID attribute on it with a value of background. I know I can use javascript but I want to use Drupal and not add any more javascript.

2条回答
太酷不给撩
2楼-- · 2019-06-04 17:29

The image render is run through theme_image_formatter() which doesn't let you set attributes.

You can get around this by building the image up manually:

$img = theme('image', array(
  'path' => $content['field_bg_image'][0]['#item']['uri'],
  'alt' => $content['field_bg_image'][0]['#item']['alt'],
  'attributes' => array('id' => 'background')
));

$content['field_bg_image'][0] = array(
  '#markup' => $img
);

echo render($content['field_bg_image']);

That's untested so let me know if you have any problems

查看更多
Deceive 欺骗
3楼-- · 2019-06-04 17:51

You could use a template for your cck field, in your case the name of this file could be field--field-bg-image.tpl.php and should be put inside your current theme folder, then you could add your id attribute like this:

 // in field--field-bg-image.tpl.php
 <div id="your-id" class="<?php echo $classes; ?>">
    <?php print render($items); ?>
 </div>    

Have a look at field.tpl.php

If you wan't to set the id on the actual img tag you could do something along these lines in your field--field-bg-image.tpl.php file:

$object = $element['#object']; 
$data = $object->field_bg_image[$object->language][0];
$fid = $data['fid'];
$width = $data['width'];
$height = $data['height'];  
print '<img id="your-id" src="'.file_create_url(file_load($fid)->uri).'" width="'.$width.'" height="'.$height.'" />';

You may also checkout theme_image() and do like this:

print theme_image(
         array('path'=>file_load($fid)->uri,
               'attributes'=>
                   array('alt'=>'','id'=>'your-id')
         )
      );
查看更多
登录 后发表回答