我有
<div>
<div id="page-wrapper" class="sidebar-content white-bg">
<div class="row border-bottom">
{% include '/layouts/navbar.html.twig' %}
</div>
{% block body %}{% endblock %}
</div>
</div>
现在在这个/layouts/navbar.html.twig
中有一个锚标记,谁的href
属性在很大程度上取决于下面呈现的模板,例如,如果它的帖子模板,href应该是/posts/new
,如果它的公告模板,href应该是/announcements/new
and等等,是那可能吗?
你可以利用全局变量_self
来解决这个问题。
main.twig
{% include "foo.twig" %}
{% include "bar.twig" %}
foo.twig和bar.twig
<div>
<div id="page-wrapper" class="sidebar-content white-bg">
<div class="row border-bottom">
{% include "nav.twig" with { 'template': _self, } %}
</div>
{% block body %}{% endblock %}
</div>
</div>
nav.twig
{% set path = '' %}
{% if template == 'foo.twig' %}
{% set path = 'path/to/foo' %}
{% elseif template == 'bar.twig' %}
{% set path = 'path/to/bar' %}
{% endif %}
{% for i in 0..3 %}
<a href="http://www.example.com/{{ path }}/{{ i }}">{{ i }}</a>
{% endfor %}
如果路径是唯一依赖于当前模板的东西,我会修改DarkBee的示例,只是简单地从父模板传递路径。这样你就不需要if / else结构了:
posts.twig:
<div>
<div id="page-wrapper" class="sidebar-content white-bg">
<div class="row border-bottom">
{% include "nav.twig" with { 'path': '/posts/new' } %}
</div>
{% block body %}{% endblock %}
</div>
</div>
announcements.twig:
<div>
<div id="page-wrapper" class="sidebar-content white-bg">
<div class="row border-bottom">
{% include "nav.twig" with { 'path': '/announcements/new' } %}
</div>
{% block body %}{% endblock %}
</div>
</div>
nav.twig:
{% for i in 0..3 %}
<a href="http://www.example.com/{{ path }}/{{ i }}">{{ i }}</a>
{% endfor %}