添加活动类以与 sf2 和 twig 链接
下面的简单代码:
<li><a href="{{ path('_list') }}">List</a></li>
如果当前页面与 _list
路由匹配,是否有一种简单的方法来添加 class="active"
?
使用最新的 symfony2 和 twig PR-Release 作为模板引擎
following simple code:
<li><a href="{{ path('_list') }}">List</a></li>
is there a simple way to add an class="active"
if the current page matches the _list
route?
using the newest PR-Release of symfony2 and twig as template engine
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
Twig 允许使用条件,并且 Request 对象在整个应用程序中可用。如果您要包含模板,则要获取要使用的路线:
如果您正在使用渲染函数,则要使用:
这样,您应该能够使用:
或更短:
Twig allows for conditionals and the Request object is available throughout the application. If you are including the template, to get the route you want to use:
If you are using the render function, you want to use:
With that, you should be able to use:
or shorter:
有时您不想对路线进行精确匹配。对于这些情况,您可以使用 twig 的“开头为”条件逻辑。
举个例子,假设您正在处理书籍。您有以下路线:book、book_show、book_new、book_edit。您希望在任何这些情况下突出显示导航项 Book。这段代码可以实现这一点。
此示例至少适用于 Symfony 2.3.x
Sometimes you don't want to do exact matching of a route. For those cases, you can use the "starts with" conditional logic of twig.
As an example, lets assume you are working with books. You have the following routes: book, book_show, book_new, book_edit. You want the navigation item Book to be highlighted for any of those cases. This code would accomplish that.
This example works with at least Symfony 2.3.x
最短版本:
有时有用:
Shortest version:
Sometimes useful:
使用三元运算符:
With ternary operator:
这是使用 symfony 3.4 完成的,但可能可以使用 SF2 完成类似的操作。
src\AppBundle\Twig\AppExtension.php
将其添加到 services.yml
用法:
This is done with symfony 3.4, but probably something similar can be done with SF2.
src\AppBundle\Twig\AppExtension.php
Add this to services.yml
Usage:
我找到了一个非常好的捆绑包,可以自动处理所有这些东西:
https://github.com/KnpLabs/KnpMenuBundle
i found a very good Bundle that handles all this stuff automagically:
https://github.com/KnpLabs/KnpMenuBundle
SF2.2
SF2.2
Symfony2.3,在Twig中,尝试这样获取uri:
Symfony2.3, in Twig, try this to get uri:
我发现更有效地了解我们是否位于活动页面和链接上:
在文件 xx.html.twig 中:
在你的头文件中
并添加 twig 的 html 类
I found more efficient to know if we are on the active page and the link or not:
in file xx.html.twig :
In on your header file
And add in html class of twig
这就是我的做法(使用 Symfony 2.6)
'_homepage'
是你的包的routing.yml
中的路由名称,路由看起来像这样This is how I do it (using Symfony 2.6)
'_homepage'
is the name of route inrouting.yml
of your bundle and the route looks like thisclass="class_name {% ifloop.index0 == 0 %}CLASSNAME{% endif %}"
class="class_name {% if loop.index0 == 0 %}CLASSNAME{% endif %}"