Paul Buciuman
Paul Buciuman

Reputation: 335

How to assign an div id a variable without using Javascript?

I'm trying to create multiple divs inside a for loop on a jsp page. I'm loading all the posts in a forum from a database, each one being a new div. I'm trying to make divs having id like id= "post-" + title, where title is a variable.

I tried with this way of puting out.printlnt(title) and is not working, I also found a solution saying to put smth like div id = {{title}} that still didn't work. Do you know if is possible to do this without using javascript? I just want to assign the id from the for loop.

for (ForumPost fp : allForumPosts) {
//get title and likes variables
<div id = "<%out.println(title);%>" >
<%out.println(title); out.println(likes);%>
<a>LIKE</a>
</div>
}

Upvotes: 1

Views: 456

Answers (2)

onyx
onyx

Reputation: 1618

Java Server Pages (JSP) is a server-side programming technology for your front-end.

Assuming that you have passed the object from your controller to JSP, then you can achieve the desired for loop with JSTL

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach items="${allForumPosts}" var="post">
    <div id="post-${post.title}"></div>
</c:forEach>

If you however prefer scriptlet (not recommended), here is how it's done

<% for (ForumPost post : allForumPosts) { %>
    <div id="post-<%=post.title%>"></div>
<% } %>

Upvotes: 1

Dmytro Grynets
Dmytro Grynets

Reputation: 953

If you don't mind using jstl (which is preferred way to scriptlets) you can do this the following way:

<c:forEach var="post" items="${allForumPosts}">
    <div id="post-${post.title}">
        ${post.title}; ${post.likes} <a>LIKE</a>
    </div>
</c:forEach>

Just make sure to include this tag at the top of your jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

If you want to use scriptlets as you do now, I think you should do something like:

<% for (ForumPost fp : allForumPosts) {%>
    <div id="post-<%out.write(fp.title)%>">
        <%out.write(fp.title)%>;<%out.write(fp.likes)%>
        <a>LIKE</a>
    </div>
<% } %>

But you really should consider using jstl instead of scriptlets

Upvotes: 1

Related Questions