Search code examples
htmlhyperlinkthymeleaf

Jump to thymeleaf-iterated section on other webpage


I try to jump to a section on another page that is an entry in a th:each loop.

I have a list of student names on one page, and clicking it will bring you to a page with more information of every user:

<div th:each="student : ${getAllStudents()}">
    <a th:href="@{linkToOtherPage}">[[${student.name}]]</a>
</div>

And on the other page with extra information for every user I have:

<div th:each="student : ${getAllStudents()}">
    <div id="studentInformation">
        <h1>[[${student.name}]]</h1>
        <h3>[[${student.age}]]</h3>
        ...
    </div>
</div>

So say that on position one in the list there is someone called Robert, and on position 20 someone called Sandy. What do I need to do in order to jump to Sandy when clicking Sandy's name?

I tried adding #studentInformation to the page with student names, so:

<div th:each="student : ${getAllStudents()}">
    <a th:href="@{linkToOtherPage}#studentInformation">[[${student.name}]]</a>
</div>

But that brings me to the top of the page.


Solution

  • If you want to link to a section using an #expression, that expression must be unique. If you use #studentInformation for each section, it doesn't know where to link to.

    If the lists are always going to be in the same order, something like this will work for you:

    First page:

    <div th:each="student, status: ${getAllStudents()}">
        <a th:href="|@{linkToOtherPage}#student${status.index}|">[[${student.name}]]</a>
    </div>
    

    Second page:

    <div th:each="student, status: ${getAllStudents()}">
        <div th:id="|student${status.index}|">
            <h1>[[${student.name}]]</h1>
            <h3>[[${student.age}]]</h3>
            ...
        </div>
    </div>
    

    (By appending the index in the array to each id, you can link to an individual student.)