2011-10-07 177 views
20

我想獲取字段的圖像路徑。我在一個節點,我需要圖像的Url爲了把它作爲內聯CSS的背景圖像。 我無法找到解決方案。你可以幫我嗎?Drupal 7獲取圖像字段路徑

回答

49

從它的URI得到的圖像的人的路:上file_create_url(

file_create_url($node->field_image['und'][0]['uri']);

更多信息)可以在這裏找到:http://api.drupal.org/api/drupal/includes%21file.inc/function/file_create_url/7

要獲取使用URI的圖像樣式創建的圖像的路徑,請使用:

在image_style_url

更多的信息()可以在這裏找到:http://api.drupal.org/api/drupal/modules!image!image.module/function/image_style_url/7

+0

救了我的命。謝謝! –

+2

這不考慮多語言字段。請參閱下面的@Gergely的答案。即使你認爲你的網站「永遠」不需要支持翻譯,請不要這樣做。欲瞭解更多信息,請參閱http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way –

+1

奇妙..它幫助 –

5

我有時也使用這樣的:

$node = node_load($nid); 
$img_url = $node->field_userimage['und'][0]['uri']; 

<img src="<?php print image_style_url($style, $img_url) ?>" /> 
+3

您還可以使用[theme_image_style()](http://api.drupal.org/api/drupal/modules--image--image.module/function/theme_image_style/7)而不是hard-使用主題函數編碼''標籤 – Laxman13

+3

會更受歡迎:'theme('image_style',array('style_name'=>'name','path'=> $ node-> field_userimage ['und'] [ 0] ['uri'],'alt'=>'Alt text'));' – Clive

+0

看起來不錯。我應該開始使用這些功能。 – Kristoffer

18

恐怕,沒有上面的解決方案是正確的。他們不遵循Drupal標準。

// field_video_image is the name of the image field 

// using field_get_items() you can get the field values (respecting multilingual setup) 
$field_video_image = field_get_items('node', $node, 'field_video_image'); 

// after you have the values, you can get the image URL (you can use foreach here) 
$image_url = file_create_url($field_video_image[0]['uri']); 

更多細節在這裏: http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

+3

上述代碼是完美的。一般來說,大多數人不需要像上面描述的那樣做,但是如果你想編寫符合Drupal標準的代碼,並且在事情發生變化或者其他情況時不會中斷,那麼就不能強調這是多麼重要。 引用代碼中的項目,比如$ object ['und'] [0] ['element']是非常糟糕的做法。始終使用field_get_items或等價物。 –

1

您也可以使用Image URL Formatter模塊。它允許改變,以便在字段格式,僅保留網址:

Drupal field settings

獎勵:它有風景的作品,以及:

enter image description here

0

獲得的影像風格網址:

$field = field_get_items('node', $node, 'field_image'); 
$image_url = image_style_url('landingpage_slider', $field[0]['uri']);