需要保留代码清洁的树枝自定义功能

需要保留代码清洁的树枝自定义功能

问题描述:

我的网站有一个菜单,我只希望能够根据用户权限显示链接。需要保留代码清洁的树枝自定义功能

菜单例如:

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

在枝杈我目前不必重复代码来完成我做·需要什么。我不喜欢这样做!

我首先检查用户是否是管理员,如果他们再然后自动获得所有的链接...

{% 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个以上的链接,所以你可以看到这不是一个正确的方法来做到这一点。

任何建议将非常欢迎如何创建一个功能在小枝(不知道任何方式来做到这一点)或建议任何其他可能的方式。我只需要有一个可重用的功能。

<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函数?这里是the doc。使用它应该使你的模板更清洁一点。

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

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

如果添加捆绑软件不适合您,那么您为什么不将自己在模板中生成的检查提取到服务中?它可以访问您的项目中几乎任何价值。您只需传递当前上下文和用户,然后获取可用于模板的布尔值数组或对象。