How to add an HTML attribute to a CCK image field

和自甴很熟 提交于 2019-12-23 03:58:27

问题


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.


回答1:


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




回答2:


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')
         )
      );


来源:https://stackoverflow.com/questions/8930110/how-to-add-an-html-attribute-to-a-cck-image-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!