alcalyn/twig-extension-onpath

为 Symfony 2 设计的 Twig 扩展,根据当前路由显示字符串(适用于活动菜单悬停)。

v1.0 2015-03-09 09:07 UTC

This package is not auto-updated.

Last update: 2024-09-18 07:29:11 UTC


README

为 Symfony 2 设计的 Twig 扩展,根据当前路由显示字符串(适用于活动菜单悬停)。

要求

- php >= 5.3.2
- Twig >= 1.0
- Symfony2 >= 2.1

安装

通过 composer

{
    "require": {
        "alcalyn/twig-extension-onpath": "dev-master"
    }
}

配置

对于 Silex,请参阅 OnPath 集成指南

对于 Symfony2,见下文

只需将其注册为一个服务。

警告:如果您使用的是 Symfony < 2.4,请勿使用此声明,而是使用下一个声明。

    twig.extension.onpath:
        class: Alcalyn\Extension\Twig\OnPath
        calls:
            - [ setRequestStack, [ @request_stack ] ]
        tags:
            - { name: twig.extension }

对于 Symfony < 2.4

    twig.extension.onpath:
        class: Alcalyn\Extension\Twig\OnPath
        scope: request
        calls:
            - [ setRequest, [ @request ] ]
        tags:
            - { name: twig.extension }

使用

您可以在您的 Twig 模板中这样做

{{ 'Hello'|onpath('home', 'user-index') }}

仅在您位于以下路由之一时显示 'Hello': homeuser-index

注意:您可以输入更多的路由名称。

例如,在菜单导航栏中可以这样操作

<nav>
    <ul>
        <li class="{{ 'active'|onpath('home') }}">
            <a href="{{ path('home') }}">Home</a>
        </li>
        <li class="{{ 'active'|onpath('blog', 'blog_post', 'blog_comment') }}">
            <a href="{{ path('blog') }}">Blog</a>
        </li>
        <li class="{{ 'active'|onpath('about') }}">
            <a href="{{ path('about') }}">About</a>
        </li>
    </ul>
</nav>