Dodzik
Dodzik

Reputation: 370

How to defeat multiplied code in Symfony2/PHP

I am writing website using Symfony2 framework and I got problem. I want to make navigation bar, which is visible on every subpage and I wonder if is there any way to achieve it without multiplying same code for every page template.

This is what I have for now in base.html.twig:

{% block navigationBar %}
        <ul class="topnav">
            <li><a class="active" href="/">Main page</a></li>
            <li><a href="/news">News</a></li>
            <li><a href="/contact">Contact</a></li>
            <ul class="topnav right";style="float:right;list-style-type:none;">
                <li><a href="/info">About</a></li>
                <li><a href="/login">Login</a></li>
            </ul>
        </ul>
{% endblock %}

and .css

ul.topnav li a.active {background-color: #4CAF50;}
ul.topnav li a:hover:not(.active) {background-color: #111;}

Parameter active shoould be set accordingly if user clicks on this element. So for example if I want to go News subpage I have to write <a class="active" href="/news">News</a></li> in template, which is responsible for given page.

I'm new in PHP and HTML programming, so if you can, please exaplain this in easts way. Thanks.

Upvotes: 1

Views: 74

Answers (1)

Heah
Heah

Reputation: 2389

A cool way using macro in twig :

{# ::macro.twig #}
{% macro navbar(route) %}
{% set path, active = route|default('/'), ' class="active"' %}
<ul class="topnav">
    <li><a href="/"{{ '/' is sameas(path) ? active }}></li>
    <li><a href="/news"{{ '/news' is sameas(path) ? active }}>News</a></li>
    <li><a href="/contact"{{ '/contact' is sameas(path) ? active }}>Contact</a></li>
    <ul class="topnav right" style="float: right; list-style-type: none;">
        <li><a href="/info"{{ '/info' is sameas(path) ? active }}>About</a></li>
        <li><a href="/login"{{ '/login' is sameas(path) ? active }}>Login</a></li>
    </ul>
</ul>
{% endmacro %}

then

{# ::base.html.twig #}
{% import 'macro.twig' as macro %}
{% block navigationBar %}
    {{ macro.navbar(app.request.attributes.get('_route')) }}
{% endblock %}

see http://twig.sensiolabs.org/doc/tags/macro.html

Upvotes: 1

Related Questions