如何为特定字段调用主题预处理函数



我在Drupal 7上,我有一个特定的tpl.php文件内容field_image: "field——field_image.tpl.php"。我需要为这个字段和我的主题创建一个预处理函数。

假设我的主题名称是"my theme"

看起来应该像

function my_theme_preprocess_field(&$variables, $hook) {
  $variables['classes_array'][] = 'aClassName';
}

但它不起作用。我错了。但是在哪里?

谢谢

您可以使用template_preprocess_field()(就像您在上面的代码中所做的那样),但只需测试特定字段是否适合您:

function my_theme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'field_image') {
      $variables['classes_array'][] = 'aClassName';
    }
  }
}

一旦你实现了钩子,不要忘记清除你的缓存,钩子实现在Drupal 7中缓存,所以在缓存被清除之前不会被拾取。

您可以在主题的template.php中声明一个mytheme_preprocess_field(&$variables, $hook),在那里您可以检查您的字段并对其标签或标记进行操作,添加类,任何事情。因此,您不需要特定于字段的tpl。——例如。

function mytheme_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#field_name'] == 'field_machine_name') {
        $variables['items'][0]['#markup'] = 'add custom markup';
  }
}

在drupal7中,您可以通过更改字段的"#markup"值来重写template_preprocess_node()中字段的输出。

你也可以使用regexp来改变任何你想要的页面内容:)

最新更新