logo

パレット - カラフルに🎨

Palette — ビジュアルページビルダー、デザインの専門知識は不要です。

ライブデモ パレットをダウンロード

Scroll

Drupalモジュールへのテーマ化テンプレートの追加

26/04/2020, by maria

Menu

第III部 Drupal 8の基本モジュール作成の実践ガイドより
.infoからテストまで、基本のみ

loremipsum.module

/**
 * Implements hook_theme().
 */
function loremipsum_theme($existing, $type, $theme, $path) {
  $variables = array(
    'loremipsum' => array(
      'variables' => array(
        'source_text' => NULL,
      ),
      'template' => 'loremipsum',
    ),
  );
  return $variables;
}

.moduleファイルをやめないもう1つの理由は、hook_theme()がまさにそこにあるからです。これはD7とほぼ同じように機能します:変数とテンプレートファイルを含む配列を宣言し、テンプレートファイルは.html.twig拡張子で正しい場所(templatesフォルダー)に保存する必要があります。

次に、レンダー配列をTwigに渡す前に、いくつかのプリプロセスを実行できます。次のフックは、各文の終わりにランダムな句読点を挿入します:

/**
 * Template preprocess function for Lorem ipsum.
 *
 * @param array $variables
 *   An associative array containing:
 *   - source_text
 */
function template_preprocess_loremipsum(&$variables) {
  $punctuation = array('. ', '! ', '? ', '... ', ': ', '; ');
  for ($i = 0; $i < count($variables['source_text']); $i++) {
    $big_text = explode('. ', $variables['source_text'][$i]);
    for ($j = 0; $j < count($big_text) - 1; $j++) {
      $big_text[$j] .= $punctuation[floor(mt_rand(0, count($punctuation) - 1))];
    }
    $variables['source_text'][$i] = implode('', $big_text);
  }
}

/templates/loremipsum.html.twig

{#
/**
 * @file
 * Default theme implementation to print Lorem ipsum text.
 *
 * Available variables:
 *   - source_text
 *
 * @see template_preprocess_loremipsum()
 *
 * @ingroup themeable
 */
#}
<div class="loremipsum">
{% for item in source_text %}
  <p>{{ item }}</p>
{% endfor %}
</div>

これで、$source_text配列は、Twig内の&

タグで囲まれた単純なforループを使用して処理されます。

hook_theme()、template_preprocess_hook()、およびTwigファイルの間の対応に注意してください:

06_0

07_0

08_0