1

How can I make some paths in the menu array limited depending on whether the user is logged on? Because I do not want the Register tab, since the user is already logged in Symfony.

{% block header %}
<div class="navbar navbar-inverse" role="navigation">
  <div class="blockMain">
      {% set mainMenu = [
        {'path': 'main',          'name': 'Home' },
        {'path': 'all',           'name': 'All' },
        {'path': 'TEST_test',     'name': 'TEST' },
        {'path': 'fos_user_profile_show',   'name': 'Profile' },
        {'path': 'fos_user_security_logout','name': 'logout'}
        {'path': 'fos_user_security_login',         'name': 'Login' },
        {'path': 'fos_user_registration_register',  'name': 'Register' }
      ] %}

    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        {% for item in mainMenu %}
          <li{{ app.request.get('_route') == item['path'] ? ' class="active"' : '' }}>
            <a href="{{ path(item['path']) }}">{{ item['name'] }}</a>
          </li>
        {% endfor %}
      </ul>
    </div><!--/.navbar-collapse -->
  </div>
</div>
{% endblock %}
Grene
  • 434
  • 6
  • 18

1 Answers1

3

You can check the role in TWIG: {% if is_granted("ROLE_USER") %}

{% block header %}
<div class="navbar navbar-inverse" role="navigation">
  <div class="blockMain">

        {% if is_granted("ROLE_USER") %}
            {% set mainMenu = [
                {'path': 'main',          'name': 'Home' },
                {'path': 'all',           'name': 'All' },
                {'path': 'TEST_test',     'name': 'TEST' },
                {'path': 'fos_user_profile_show',   'name': 'Profile' },
                {'path': 'fos_user_security_logout','name': 'logout'}
            ] %}          
        {% else %}
            {% set mainMenu = [
                {'path': 'main',          'name': 'Home' },
                {'path': 'fos_user_security_login',         'name': 'Login' },
                {'path': 'fos_user_registration_register',  'name': 'Register' }
            ] %}          
        {% endif %}

    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        {% for item in mainMenu %}
          <li{{ app.request.get('_route') == item['path'] ? ' class="active"' : '' }}>
            <a href="{{ path(item['path']) }}">{{ item['name'] }}</a>
          </li>
        {% endfor %}
      </ul>
    </div><!--/.navbar-collapse -->
  </div>
</div>
{% endblock %}
janek1
  • 256
  • 1
  • 3
  • 17
  • 1
    `{% if app.user %}` check for logged in user regardless of the role. See https://stackoverflow.com/a/23612913/1751591 – Zain Saqer May 23 '17 at 21:45