【问题标题】:Accessing variables in twig override templates访问 twig 覆盖模板中的变量
【发布时间】:2021-02-15 03:02:06
【问题描述】:

这是我所在的地方:

我下载了组模块,为组创建了自定义字段,然后在页面本身上我用树枝模板(page--group.html.twig)覆盖了它。现在的问题是,如何将自定义字段从组(字段的机器名称为“group_picture”)传递到页面的树枝模板--group.html.twig?

我使用kint() 来查看是否有任何东西从群组中传下来,但没有任何东西被传下来。我在这里错过了什么?

顶级kint()变量:

'page' => array(33)
'theme_hook_original' => string(4) "page"
→'attributes' => Drupal\Core\Template\Attribute(1)
→'title_attributes' => Drupal\Core\Template\Attribute(1)
→'content_attributes' => Drupal\Core\Template\Attribute(1)
'title_prefix' => array(0)
'title_suffix' => array(0)
'db_is_active' => boolTRUE
'is_admin' => boolTRUE
'logged_in' => boolTRUE
→'user' => Drupal\Core\Session\AccountProxy(7)
→'directory' => string(23) "themes/custom/kropotkin"
→'base_path' => string(1) "/"
→'front_page' => string(1) "/"
→'language' => Drupal\Core\Language\Language(5)
'is_front' => boolFALSE
→'#cache' => array(1)
→'#attached' => array(1)
→'navbar_top_attributes' => Drupal\Core\Template\Attribute(1)
→'navbar_attributes' => Drupal\Core\Template\Attribute(1)
→'sidebar_first_attributes' => Drupal\Core\Template\Attribute(1)
→'sidebar_second_attributes' => Drupal\Core\Template\Attribute(1)
'container_navbar' => string(1) "0"
'container' => string(9) "container"
→'theme_hook_suggestions' => array(3)
'theme_hook_suggestion' => string(4) "page"

我的树枝覆盖目前是这样的:

{% extends "@themename/page.html.twig" %}

{% block content %}
    {{kint()}}
    BLAH BLAH
{% endblock %}

page.html.twig 直接来自 bootstrap_barrio 的子主题模板。

【问题讨论】:

  • 你可以通过发布树枝代码来详细说明吗?
  • 它们不在 {{content}} 变量中吗?我希望它们与所有其他实体一样。当然,如果您已将字段设置为在组类型的“管理显示”页面上可见。另外,您确定要覆盖正确的模板吗?组模块似乎有它的own templates
  • @2pha 不是。我将发布 kint 提供的变量。
  • 同样kint(content)返回null
  • 另外根据我在inspect中的twig调试,它建议使用page--group.html.twig和覆盖选项之一。

标签: twig drupal-8


【解决方案1】:

使用 Drupal 核心的默认渲染引擎,您无法从 page--group.html.twig 访问 group.html.twig 的变量。您必须手动完成。

您可以实现hook_preprocess_HOOK 从组字段中检索数据,然后将其传递给模板:

  • 在您的主题文件中(假设它是 your_theme.theme):
    function your_theme_preprocess_page(&$variables) {
      $group_id = \Drupal::routeMatch()->getRawParameter('group'); // get group ID from route
      if (!empty($group_id)) {
        $group = \Drupal\group\Entity\Group::load($group_id); // load group entity
        $field_text = $group->get('field_text')->value; // get field value you want, here I use a text field for example            
        $variables['group_field_text'] = $field_text; // store it in $variables, so you can access it in template
      }
    }
    
  • 在您的 page.html.twig 中:
    {{ group_field_text }}
    

【讨论】:

  • 谢谢你 - 有没有办法可以在 .theme 文件中找到我可以使用的所有 drupal 函数的列表?
  • @Majo0od Here 是钩子函数的列表。请注意,.theme 文件中只能实现某些挂钩。阅读更多关于here
猜你喜欢
  • 2012-05-04
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
相关资源
最近更新 更多