needs_context 的 Twig 函数

Twig function with needs_context

我需要在函数的 needs_context 中获取 current_page。 它工作正常,但 needs_context 仍然是空的。

我的 class 助手扩展了 \Twig_Extension

class Helpers extends \Twig_Extension {

public function getName() {
    return 'Helpers';
}

public function getFunctions() {
    return [
        new \Twig_SimpleFunction('activeClass', [
            $this,
            'activeClass'
        ], [
            'needs_context' => true
        ])
    ];
}

  public function activeClass($context, $page) {
    if (isset($context['current_page']) && $context['current_page'] === $page){
        return ' active ';
    }
}

在我的 .twig 文件中 <a href="" class="{{ activeClass('foo') }}">Foo</a>

我希望通过此功能可以return active class 获得导航栏中的当前href。我使用 Slim v3 和他的扩展 Twig-view。

感谢您的帮助。

我解决了这个问题。 因为我为 Slim 使用了 Twig 的扩展而不是 Twig,所以它是不同的。 通常,我们使用 needs_context 来提取 current_page 的值。 但是对于 Slim PHP 的 Twig-view,我们可以使用 {% if is_current_path('your_page') %}class="active"{% endif %}

衷心感谢@martias 和@DarkBee 的帮助。