【问题标题】:Drupal 7 Get image field pathDrupal 7 获取图像字段路径
【发布时间】:2011-12-02 21:25:11
【问题描述】:

我想获取一个字段的图像路径。我在一个节点中,我需要图像的 Url 才能将其作为内联 css 中的背景图像。 我找不到解决方案。你能帮帮我吗?

【问题讨论】:

    标签: drupal drupal-7


    【解决方案1】:

    从 URI 中获取图像的路径:

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

    关于 file_create_url() 的更多信息可以在这里找到:http://api.drupal.org/api/drupal/includes%21file.inc/function/file_create_url/7

    要从其 URI 中获取使用图像样式创建的图像的路径:

    image_style_url($style, $node->field_image['und'][0]['uri']);

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

    【讨论】:

    • 这不考虑多语言字段。请参阅下面@Gergely 的答案。即使您认为您的网站“从不”需要支持翻译,请不要这样做。有关详细信息,请参阅computerminds.co.uk/articles/…
    【解决方案2】:

    恐怕,以上解决方案都不正确。他们不遵循 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

    【讨论】:

    • 以上代码完美。通常大多数人不需要像上面描述的那样做,但是如果你想编写符合 Drupal 标准并且在事情发生变化时不会中断的代码,那么就不能强调这是多么重要。像 $object['und'][0]['element'] 这样在代码中引用项目是非常糟糕的做法。始终使用 field_get_items 或等效项。
    • 这是一个老问题,但是当谈到在 Drupal 中获取字段值时,互联网上充斥着不良做法,这个问题应该得到更多关注,因为它是正确的方法。正如 Jamie Hollern 已经写的那样,你永远不应该使用很多人推荐的 ['und'][0] 东西。
    【解决方案3】:

    我有时会用这个:

    $node = node_load($nid);
    $img_url = $node->field_userimage['und'][0]['uri'];
    
    <img src="<?php print image_style_url($style, $img_url) ?>" />
    

    【讨论】:

    • 你也可以使用theme_image_style()而不是硬编码&lt;img&gt;标签
    • 最好使用主题功能:theme('image_style', array('style_name' =&gt; 'name', 'path' =&gt; $node-&gt;field_userimage['und'][0]['uri'], 'alt' =&gt; 'Alt text'));
    • 看起来不错。我应该开始使用这些功能。
    • Computed Field中,我只能通过这种方法访问图像字段uri
    【解决方案4】:

    您也可以使用Image URL Formatter 模块。它允许更改字段格式以仅获取 URL:

    奖励:它也适用于视图:

    【讨论】:

      【解决方案5】:

      获取图片样式url:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-19
        • 1970-01-01
        相关资源
        最近更新 更多