Drupal 8:在树枝中列出具有活动 class 的分类术语
Drupal 8: List taxonomy terms with active class in twig
假设我有一个分类名称 Flavor,术语有 Vanilla、Chocolate 和 Green Tea。
我在 'Flavor' 分类法下还有一个内容类型名称 ice-cream,其风味字段可以是多个 select。
我创建了一个名为 Baskin Robin 的冰淇淋页面,并在风味字段下勾选了 'Vanilla' 和 'Chocolate'。
如何列出 node.html.twig 中的所有 'Flavor' 项并为 'Vanilla' 和 'Chocolate' 添加 class?
例如:
<div class="field-item active">Vanilla</div>
<div class="field-item active">Chocolate</div>
<div class="field-item">Green Tea</div>
您需要 块 或 视图 才能做到这一点。
您还可以使用 hook_preprocess_node 在冰淇淋模板中注入所有口味。
- Here the documentation 创建自定义块。
- Here the documentation 创建视图块。
- Here the documentation 放置块(自定义或视图)。
我将解释实现您的目标的最简单和最快但最脏的方法 - 使用 hook_preprocess_node.
我建议使用自定义块或视图以实现可伸缩性和可维护性。下面的代码是一个工作示例,您可以在自定义块中使用它。
这里使用预处理方式的代码
在您的 template.theme
文件中:
/**
* Implements hook_preprocess_node.
*/
function template_preprocess_node(&$variables) {
$node = $variables['node'];
if($node->bundle() == 'ice-cream') {
// Should be injected.
$termStorage = \Drupal::entityManager()->getStorage('taxonomy_term');
// Load all flavors taxonomy term.
$variables['flavors'] = $termStorage->loadTree('flavors', 0, NULL, TRUE);
}
}
在你的node.html.twig
或node--ice-cream.html.twig
中:
{% for flavor in flavors %}
{% set classes = ['field-item'] %}
{% for node_flavor in node.field_flavors if node_flavor.target_id == flavor.id %}
{% set classes = classes|merge(['active'])%}
{% endfor %}
<div class="{{ classes|join(' ') }}">{{ flavor.name.value }}</div>
{% endfor %}
希望对您有所帮助!
假设我有一个分类名称 Flavor,术语有 Vanilla、Chocolate 和 Green Tea。
我在 'Flavor' 分类法下还有一个内容类型名称 ice-cream,其风味字段可以是多个 select。
我创建了一个名为 Baskin Robin 的冰淇淋页面,并在风味字段下勾选了 'Vanilla' 和 'Chocolate'。
如何列出 node.html.twig 中的所有 'Flavor' 项并为 'Vanilla' 和 'Chocolate' 添加 class?
例如:
<div class="field-item active">Vanilla</div>
<div class="field-item active">Chocolate</div>
<div class="field-item">Green Tea</div>
您需要 块 或 视图 才能做到这一点。 您还可以使用 hook_preprocess_node 在冰淇淋模板中注入所有口味。
- Here the documentation 创建自定义块。
- Here the documentation 创建视图块。
- Here the documentation 放置块(自定义或视图)。
我将解释实现您的目标的最简单和最快但最脏的方法 - 使用 hook_preprocess_node.
我建议使用自定义块或视图以实现可伸缩性和可维护性。下面的代码是一个工作示例,您可以在自定义块中使用它。
这里使用预处理方式的代码
在您的 template.theme
文件中:
/**
* Implements hook_preprocess_node.
*/
function template_preprocess_node(&$variables) {
$node = $variables['node'];
if($node->bundle() == 'ice-cream') {
// Should be injected.
$termStorage = \Drupal::entityManager()->getStorage('taxonomy_term');
// Load all flavors taxonomy term.
$variables['flavors'] = $termStorage->loadTree('flavors', 0, NULL, TRUE);
}
}
在你的node.html.twig
或node--ice-cream.html.twig
中:
{% for flavor in flavors %}
{% set classes = ['field-item'] %}
{% for node_flavor in node.field_flavors if node_flavor.target_id == flavor.id %}
{% set classes = classes|merge(['active'])%}
{% endfor %}
<div class="{{ classes|join(' ') }}">{{ flavor.name.value }}</div>
{% endfor %}
希望对您有所帮助!