在Drupal 8中对特定节点类型使用预处理钩子 [英] Using preprocess hook on specific node type in Drupal 8

查看:117
本文介绍了在Drupal 8中对特定节点类型使用预处理钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功使用了预处理页面挂钩,例如:

I've had success using preprocess page hooks such as:

function mytheme_preprocess_page__node_front(&$variables) {
    ...
}

function mytheme_preprocess_page__node_12(&$variables) {
    ...
}

分别与名为page--front.html.twig和page--12.html.twig的自定义模板相关.

which correlate with custom templates named page--front.html.twig and page--12.html.twig, respectively.

我正在尝试为称为视频的内容类型实现相同的挂钩和模板配对.我知道示例之间是针对特定页面的自定义模板,而我的目标是针对整个内容类型的自定义模板,但是我得到了一个名为node--video.html.twig的自定义模板,该模板可以用作所有视频页面的模板.但是,当我尝试根据此模板名称编写钩子时:

I'm trying to implement the same hook and template pairing for a content type called Video. I understand that there is a difference in that my examples have been custom templates for specific pages while my goal is a custom template for an entire content type, but I got a custom template called node--video.html.twig that works as a template for all video pages. However when I try to write a hook based on this template name:

function mytheme_preprocess_node__video(&$variables) {
    ...
}

这不起作用.我想我要么不能定义这样的钩子,要么我只是错误地命名了它.我发现了一些与此相关的线程,例如,这似乎暗示我需要定义所有节点的钩子,然后编写一个if语句来分别处理每种类型. 所以....

this does not work. I think that I either can't define a hook like this, or I'm just naming it incorrectly. I found a couple threads somewhat relating to this such as this that seem to imply that I need to define a hook for all nodes and then write an if statement that handles each type separately. So.......

最后一个问题 :我可以为整个内容类型定义一个钩子吗?如果是的话,我在做什么错了?

Final Question: Can I define a hook for an entire content type, and if so what am I doing wrong?

推荐答案

在预处理器中使用条件获取节点类型,然后在其中执行逻辑或调用另一个函数.

Use condition within the preprocessor to get the node type and then either do your logic within, or invoke another function.

function mytheme_preprocess_node(&$variables) {
  switch ($variables['node']->getType()) {
    case "video":
      // ...
    break;
    case "something_else":
      // ...
    break;
  }
}

从理论上讲,您可以尝试调用名为mytheme_preprocess_node__" . $variables['node']->getType()的函数(如果存在的话)来模拟您要实现的目标,但是如果没有明显的好处,它会大惊小怪.

You could in theory emulate what you are trying to achieve by trying to invoke a function named mytheme_preprocess_node__" . $variables['node']->getType() if it exists, but is too much fuss without a clear benefit.

这篇关于在Drupal 8中对特定节点类型使用预处理钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆