需要Twig自定义功能以保持代码清洁

时间:2014-09-30 03:48:40

标签: php symfony twig

我的网站有一个菜单,我只希望能够根据用户权限显示链接。

菜单示例:

<ul>
     <li>Dashboard</li>
     <li>Products</li>
     <li>Suppliers</li>
</ul>

在Twig中,我目前不得不重复代码来完成我需要做的事情。我不喜欢这样做!

我首先检查用户是否是管理员,然后他们会自动访问所有链接......

    {% set is_admin = false %}
    {% if app.security.token.user.roles is iterable %}
        {% for role in app.security.token.user.roles %}
            {% if role == 'ROLE_ADMIN' or role == 'ROLE_SUPER_ADMIN'  %}
                {% set is_admin = true %}
            {% endif %}
        {% endfor %}
    {% endif %}

这是我目前设置的菜单。我需要能够根据用户角色和权限验证链接是否可以显示。这只是模拟链接,但实际上我可以有超过50个链接,所以你可以看到这不是一个正确的方法来做到这一点。

对于如何在Twig中创建函数(不知道任何方法)或建议的任何其他可能方式,我们非常欢迎任何建议。我只需要一个可重用的功能。

<ul>
     {% set is_dashboard = false %}
     {% for role in app.user.roles %}
        {% for roleAuth in role.appRoleAuthorizations %}
            {% for roleAuthRoute in roleAuth.appRoleAuthorizationRoute %}
                {% if roleAuthRoute.name == "dashboard" or is_admin %}
                   {% set is_dashboard = true %}
                {% endif %}
                {% if not loop.last %}{% endif %}
            {% endfor %}
            {% if not loop.last %}{% endif %}
        {% endfor %}
        {% if not loop.last %}{% endif %}
     {% endfor %}
     {% if is_dashboard == true %}
          <li>Dashboard</li>
     {% endif %}


     {% set is_products = false %}
     {% for role in app.user.roles %}
        {% for roleAuth in role.appRoleAuthorizations %}
            {% for roleAuthRoute in roleAuth.appRoleAuthorizationRoute %}
                {% if roleAuthRoute.name == "product" or is_admin %}
                   {% set is_products = true %}
                {% endif %}
                {% if not loop.last %}{% endif %}
            {% endfor %}
            {% if not loop.last %}{% endif %}
        {% endfor %}
        {% if not loop.last %}{% endif %}
     {% endfor %}
     {% if is_products == true %}
          <li>Products</li>
     {% endif %}

     {% set is_suppliers = false %}
     {% for role in app.user.roles %}
        {% for roleAuth in role.appRoleAuthorizations %}
            {% for roleAuthRoute in roleAuth.appRoleAuthorizationRoute %}
                {% if roleAuthRoute.name == "supplier" or is_admin %}
                   {% set is_suppliers = true %}
                {% endif %}
                {% if not loop.last %}{% endif %}
            {% endfor %}
            {% if not loop.last %}{% endif %}
        {% endfor %}
        {% if not loop.last %}{% endif %}
     {% endfor %}
     {% if is_suppliers == true %}
          <li>Suppliers</li>
     {% endif %}

</ul>

1 个答案:

答案 0 :(得分:2)

为什么不使用Symfony的内置{% is_granted() %} Twig功能?这是the doc。使用它应该使您的模板更加干净。

至于构建菜单,您无需在模板中执行此操作,因为这会破坏单一责任原则。

首先,您应该考虑使用KnpMenuBundle,因为它允许您动态构建菜单,这些菜单基本上可以依赖于可通过服务容器访问的任何参数。菜单本身通常使用EventListeners构建,这为您提供了很大的灵活性。

如果您无法选择添加捆绑包,那么为什么不将模板中的检查提取到服务本身?它几乎可以访问项目中的任何值。你可以在那里传递当前的上下文和用户,并获得一个可以在你的模板中使用的布尔数组或对象。

相关问题