如何在 Drupal 8 中 customize/style/theme 自定义内容类型的输出?

How to customize/style/theme the output of a custom content type in Drupal 8?

我正在创建自己的 Drupal 8 "classy" sub-theme。现在我用一些文本字段创建了一个名为 "s-box" 的内容类型。我还创建了一个名为 "scol" 的视图,它是 "s-box" 的列表。此 "scol" 作为一个块添加到站点的侧边栏。

效果很好(这意味着显示所有内容)但我希望某些内容类型字段嵌套在特定标记中(如 h4 中的标题)。最好,我想为此内容类型 "s-box" 自定义整个输出。

但是我想不通,树枝应该叫什么名字。到目前为止我试过:

node--s-box.html.twig (what I thought would be the correct name)  
block--scol.html.twig  
field--node--s-box.html.twig  
field--s-box.html.twig  
node--scol.html.twig  
scol--s-box.html.twig

完美的解决方案是一个模板,我可以在其中构建自己的 html 并分配内容类型的字段。

只需启用 Twig 调试。参见 Debugging Twig templates。启用 Twig 调试后,您将获得模板命名建议,作为 HTML 评论直接打印到您的标记中。在那里你会看到这个模板应该如何准确命名。


您的 sites/development.services.yml 应该如下所示:

# Local development services.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
      debug: true
      auto_reload: true
      cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

并且您需要将以下行添加到您的 settings.phpsettings.local.php:

/**
 * Enable local development services.
 */
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';

最终会给你这样的东西:

<!-- FILE NAME SUGGESTIONS:
   * node--page--j1.html.twig
   * node--1--full.html.twig
   * node--1.html.twig
   * node--page--full.html.twig
   * node--page.html.twig
   * node--full.html.twig
   x node.html.twig
-->

别忘了清除缓存!多次。

解决方案是:

因为我的内容类型在视图中,所以我可以访问 views-view-fields--[my-view].html.twig 中的所有字段(在我的例子中:views-view-fields--scol.html.twig

键是 fields 数组。我可以通过他们的机器名称访问所有字段。喜欢 fields.title.contentfields.field_foo.content.

因此我可以在此处设置 s-box 的整个输出的样式。