-1

我正在使用 drupal 7.x 并正在创建一个节点内容类型模板。我的内容类型有多个自定义字段,包括一个图像字段。我正在尝试将图像字段及其属性添加到节点模板。我可以使用显示图像

print render($content['field_custom_image'][0])

但是我也想显示文件名和标题文本。我尝试了下面的代码,但它没有显示任何内容。

print render($content['field_custom_image'][0]['und']['title'])

在 Drupal 6 中,我可以使用:

print $node->field_custom_image[0]['data']['description']

我执行时print_r($node)的输出如下。

[field_reclaimer_image] => Array ( [und] => Array ( [0] => Array ( [fid] => 8 [alt] => [title] => 测试标题 [width] => 1117 [height] => 651 [uid] => 1 [文件名] => 24-1033_angle_02_1339771175.jpg [uri] => public://images/24-1033_angle_02_1339771175.jpg [filemime] =>…
4

2 回答 2

1

你可以这样做:

echo $node->field_custom_image['und'][0]['filename'];

echo $node->field_custom_image['und'][0]['title'];

und 和 0 是错误的方式。如果你把你的print_r()in<pre>标签包装起来,你会看到一个格式更好的数组,它更容易阅读。

于 2012-06-22T12:39:30.120 回答
1

如果您有权访问节点对象,则应使用field_get_items(),它根据字段将使用的语言(通常是与节点关联的语言)返回字段的值。我将使用以下代码来打印第一张图像中的信息。

$values = field_get_items('node', $node, $field_name);
if (!empty($values)) {
  print $values[0]['title'];
  print $values[0]['description'];
}

render()在这种情况下,因为您正在渲染字符串,所以没有必要。在这种情况下,函数所做的只是返回作为参数传递的值。

function render(&$element) {
  if (is_array($element)) {
    show($element);
    return drupal_render($element);
  }
  else {
    // Safe-guard for inappropriate use of render() on flat variables: return
    // the variable as-is.
    return $element;
  }
}

如果您尝试渲染的值可能是字符串或渲染数组,那么使用render().

我在我的测试站点中尝试了以下代码。我正在加载的节点包含一个图像字段。

$node = node_load(8);
$values = field_get_items('node', $node, 'field_image');

dsm($values);

显示的是dsm()以下内容。

截屏

返回的数组可以包含多个元素,具体取决于字段设置。准备好处理多个图像。

使用field_get_items(),您无需处理语言。对于某些字段,语言 ID 可以是“und”,用于具有不依赖于语言的值的字段;对于其他字段,要使用的正确值可能是节点的一组。

还要考虑一些模块可以更改与字段关联的值,并且使用“und”不一定是正确的做法,对于那些包含“und”数组索引的有效值的字段也是如此。

于 2012-06-22T14:47:58.353 回答