Twig自定义函数需要保持代码清洁


Twig Custom Function Needed To Keep Code Clean

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

菜单示例:

<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>

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

至于构建菜单,没有必要在模板中这样做,因为这将打破单一责任原则。

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

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