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>
}
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
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>
<% } %>
Related
I have a array containing some html content like this.
const articleArray=['<p>first text</p>\r\n','<p>second text></p>\r\n','<p>third text</p>\r\n']
I need to render this in an ejs file through a get request
request.render('viewArticles',{array : articleArray})
where 'viewArticles' is an ejs file. I have used the middleware to set the view engine as ejs.
This is the code in ejs
<% for(arr in array) {%>
arr
<% } %>
I am not able to render any html. How to solve this?
'<%- %>' this is help to print html code as it is.
<% 'Scriptlet' tag, for control-flow, no output
<%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline
_%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it
for refrence please click visit this site EJS
<% array.forEach(function(item) {%>
<%-item%>
<% }) %>
Try this
<% array.forEach(function(item,index){ %>
<%= item %>
<% }) %>
I'm not really sure how to do what you want exactly , but take a look at this:
First, instead of you creating an array of HTML elements, how about you create an array of objects, like so :
const articles = [{text: "first text"} , {text: "second text"}, {text: "third text"}];
this way you just have to write the HTML once, and I am fairly new to programming but I don't see a scenario where you would get a response in HTML, usually you query a database for data or from a JSON file... and assuming the array is actually getting passed to the .ejs file, lets iterate though it,
<% for(let a of articles){ %>
<p> <%= a.text %> </p>
</br>
<% } %>
If the array is NOT getting passed, check for these in your code :
// If you installed
..."dependencies" : {
"ejs": "x.x.x",
} //Check the package.json file
// If you imported correctly
import ejs = require("ejs");
// If you specified the views path
app.set("views", path.join(__dirname, "views"));
// And the views engine
app.set("view engine", "ejs");
// And your route
request.render('viewArticles',{ articles : articles }) // Check if the file name is correct, I get this wrong many times
In my controller:
#xxxs = XXX.page(params[:page] || 1).per(10)
In my view:
<div class="turn_page>
<%= paginate #xxxs, window: 2 %>
</div>
Why the content in the end of the font is repeated again, but inside the tag, only the link has no html content
Ok so i am trying to make a JSP tag (via tagfile). It let's you create tables that come with an "add" button, that lets you adds rows at client side. So basically you pass the HTML for the row to this tag, and it creates a table to contain that row, and also outputs the JS for the dynamic insertion of said row to the table. And you also pass a row which simply becomes the header of the table.
<%# tag language="java" pageEncoding="ISO-8859-1"%>
<%# taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c' %>
<%# taglib uri='http://java.sun.com/jsp/jstl/functions' prefix='fn' %>
<%# taglib uri='http://java.sun.com/jsp/jstl/xml' prefix='x' %>
<%# attribute name = "id" required = "true"%>
<jsp:doBody var = "thebody"/>
<x:parse doc='${"<root>"}${thebody}${"</root>"}' var = "xmlBody"/>
<table id = "${id}" class = "datatable">
<tbody>
<tr>
<x:forEach select="$xmlBody/root/th/*" var="data">
<td><x:out select="$data"/></td>
</x:forEach>
</tr>
<tr>
<x:forEach select="$xmlBody/root/tr/*" var="data">
<td><x:out select="$data"/></td>
</x:forEach>
</tr>
<c:out value="${heading}"/>
</tbody>
</table>
<button id="addRowButton" class="BUTTON btndarkblue " title="Add" onclick="addRowTo${id}()"> Add </button>
<script>
function addRowTo${id}()
{
$('#${id} tr:last').after('<tr><x:forEach select="$xmlBody/root/tr/*" var="data"><td><x:out select="$data"/></td></x:forEach></tr>');
}
</script>
Now, this is working perfectly when the tags contain simple text. But when i pass some html (directly or via other custom jsp tags), it outputs only the TEXT of those tags, and not the tags themselves. Eg:
<button onclick = "doSomething()">Click here</button>
becomes
Click Here
I believe what it is doing, is that the tag, when applied to a non-leaf node, outputs only the data at the leaf-nodes down that chain...
So does anybody have a workaround for this? How make it output the nodes as it is?
PS: i tried the c:out as well, but that outputted the html as TEXT ( $lt;tr $gt; ...)
could you help please?, how I can read the variable objd in a <% ... %> Assigned in the foreach?
<c:forEach var="objd" items="${beanDreqproducto}">
<%
Gson j = new Gson();
String data = j.toJson(objd);
%>
console.log("${objd.cantidad}, data: "+'${data}');
</c:forEach>
The ${} basically translates to PageContext#findAttribute(). So, this should do:
<%
Object objd = pageContext.findAttribute("objd");
// ...
%>
Note that you should set data in page scope as well in order to get ${data} to work:
<%
// ...
pageContext.setAttribute("data", data);
%>
See also:
Our EL wiki page
Unrelated to the concrete question, this approach is ultimately bad. You should choose to use either JSTL/EL or scriptlets exclusively, not both. If you prefer JSTL/EL, just create a custom EL function to do the desired job, so that you can end up something like as follows:
<c:forEach var="objd" items="${beanDreqproducto}">
console.log("${objd.cantidad}, data: ${my:toJson(objd)}");
</c:forEach>
Our EL wiki page contains a section how to create EL functions.
I'm trying to find a better way to use a div table with ASP.NET MVC, the problem I see is that you need to do loads of looping, rather than one loop if I had to use a traditional <table> table.
Example
<div class="column">
<div class="row">Name</div>
<% foreach (Person person in (List<Person>)ViewData.Model) {%>
<div class="row"><%= Html.Encode(person.Name) %></div>
<%} %>
</div>
<div class="column">
<div class="row">Email</div>
<% foreach (Person person in (List<Person>)ViewData.Model) {%>
<div class="row"><%= Html.Encode(person.Email) %></div>
<%} %>
</div>
<div class="column">
<div class="row">Phone</div>
<% foreach (Person person in (List<Person>)ViewData.Model) {%>
<div class="row"><%= Html.Encode(person.Phone) %></div>
<%} %>
</div>
If it looks like a table and smells like a table why not use a table?
But if you want to do it in this way well try to build a extention method for your Html property that generates this html code and have the list as a parameter and maybe a list for your columns, To generate your html code you can use the TagBuilder class.
It's rather subjective issue, but I think you don't really need to use divs to do so, coz you are simply displaying table of data and this is why we need "table" tag.
The introduction of div and CSS layout is not to replace the table tag, but to free table tag from doing formatting and layout job.
Edit
Moreover, you can still do your job in one loop. Rather than loop through columns, why not loop through rows (name, phone... )
<% foreach(Person person in (List<Person>)ViewData.Model)) %>
<div class="row">
Name: <%= Html.Encode(person.Name) %>
Email: <%= Html.Encode(person.Email) %>
...
</div>
Although I personally still prefer using table (together with tr and td) instead.
If you are dislaying tabular data, that's why the table tag is there. People only suggest div, instead of table when it's about layout. So it's perfectly OK to use the table tag when you are displaying key-value type of information.
I agree with what everyone else have said (that you really should just use a table) - however I will try to come up with a solution to your issue too.
I don't think there's an elegant way to overcome the "loop more than once" issue, but at the very least we can make it a bit "easier" to add new columns to the list:
var myList = (List<Person>)ViewData.Model;
var myColumns = new Dictionary<string, List<string>>();
myColumns.Add("Name", new List<string>());
myColumns.Add("Email", new List<string>());
myColumns.Add("Phone", new List<string>());
foreach(var person in myList){
myColumns["Name"].Add(Html.Encode(person.Name));
myColumns["Email"].Add(Html.Encode(person.Email));
myColumns["Phone"].Add(Html.Encode(person.Phone));
}
Then now you can do this:
<% foreach(var column in myColumns){ %>
<div class="column">
<div class="row"><%= column.Key %></div>
<% foreach (string value in column.Value) {%>
<div class="row"><%= value %></div>
<%} %>
</div>
<% } %>
It is still poor performance compared to using the -tag and really I don't see why you'd want to avoid that in this scenario.