web-dev-qa-db-ja.com

相対または外部URLを使用して画像を表示するにはどうすればよいですか?

単純な問題のようですが、単純な解決策を見つけることができません。

基本的に、画像の相対URLを持つ別のデータベースからコンテンツタイプを取り込むフィードモジュールがあります。すなわち。 /images/image1.jpg

この値をテキストフィールドタイプに格納しています。

このフィールドの出力を<img src="$value">に簡単に変換する方法はありますか?

1
Jiminy Cricket

確かに、Drupal 7と仮定すると、カスタムモジュールでこのための独自のフィールドフォーマッタを作成できます。

/**
 * Implements hook_field_formatter_info().
 */
function YOURMODULE_field_formatter_info() {

  $info = array();

  $info['image_source_formatter'] = array(
    'label' => t('Image Source Formatter'),
    'description' => t('Display the image sourced in this field.'),
    'field types' => array('text'),
  );

  return $info;

}

/**
 * Implements hook_field_formatter_view().
 */
function YOURMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'image_source_formatter':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#theme' => 'image',
          '#path' => $item['safe_value'], // you can also set '#height', '#width', '#alt', '#title' and '#attributes' here as well, see theme_image() for more details
        );
      }
      break;

  }

  return $element;

}

キャッシュをクリアして安全な側にし、このフィールドにこの新しいフィールドフォーマッターを使用できます。たとえば、コンテンツタイプの[ディスプレイの管理]に移動して、これを選択できます。

enter image description here

プレーンテキストフィールドの場合、テキストを出力する代わりに、テキストを画像へのパスとしてテーマ化します。

このフィールドでは、sites/default/files/foo.jpg必要に応じてローカルでソースするか、またはhttp://www.example.com/foo/bar/baz.jpgも機能します。これは theme( 'image'、$ variables) を呼び出し、パスをこのフィールドの値に設定します。

補足: RL Formatter および Simple Field Formatter モジュールは、独自のカスタムモジュールを作成したくない場合に、これを行うように見えます。

1
Jimajamma

これを行う最も簡単な方法は、フィールドテンプレートを上書きすることです。

フィールド名-[フィールド名] .tpl.php

マークアップを追加するだけです

例:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><img src="<?php print render($item); ?>" /></div>
    <?php endforeach; ?>
  </div>
</div>

$ items配列は、その項目の情報の配列を提供し、renderを使用して出力をレンダリングします。詳細については、drupal apiのフィールドテンプレートを参照してください https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/ 7

Display suite https://drupal.org/project/ds を使用している場合は、カスタムモジュールを作成して、トークンモジュールと一緒にその値を出力できます。詳細については、このブログ投稿を参照してください: http://www.elevatedthird.com/blog/using-custom-fields-display-suite-drupal-7

0
chadpeppers