JoePear JoePear - 4 months ago 10
HTML Question

How can I put a block inside a tag to change the class?

This is what I have on the base class

<ul class="nav navbar-nav side-nav">
<li>
<a href="#" th:href="@{/home}">Home</a>
</li>

<li class="active">
<a href="#" th:href="@{/page}">My Page</a>
</li>
</ul>


The
class="active"
is a class that makes the side navigation bar highlight the appropriate tab that the user is on. I have done this manually for each page but I know with
Thymeleaf
you can have a base class and just tag the things you want changed on the page and replace them with new content.

This is what I had so far...
base.html


<ul class="nav navbar-nav side-nav">
<li>
<a href="#" th:href="@{/home}">Home</a>
</li>

<li th:include="this :: active">
<a href="#" th:href="@{/page}">My Page</a>
</li>
</ul>


page.html


<ul class="nav navbar-nav side-nav" th:fragment="active">
<li class="active">
<a href="#" th:href="@{/page}">My Page</a>
</li>
</ul>


But my question is.. Is it possible for me to just replace the word
active
for
class="active"
in the
<li>
tag?

Thanks in advance :)

Answer

can you try this and tell if this worked for you

base class

<ul class="nav navbar-nav side-nav">
    <li>
        <a href="#" th:href="@{/home}">Home</a>
    </li>

    <li th:classappend="${#httpServletRequest.getRequestURI() == '/page' ? 'active':''}">
        <a href="#" th:href="@{/page}">My Page</a>
    </li>
    <li th:classappend="${#httpServletRequest.getRequestURI() == '/otherpage' ? 'active':''}">
        <a href="#" th:href="@{/otherpage}">My Other Page</a>
    </li>
</ul> 

and in page.html delete the active class

<ul class="nav navbar-nav side-nav" th:fragment="active">
        <a href="#" th:href="@{/page}">My Page</a>
</ul>
Comments