1

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?

loksan
  • 157
  • 3
  • 17

3 Answers3

1

Try this

<% array.forEach(function(item,index){ %>
        <%= item %> 
    <% }) %>
Shantun Parmar
  • 432
  • 2
  • 13
1

'<%- %>' 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%> <% }) %>

Nilesh Chavan
  • 361
  • 3
  • 10
0

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

PedroMiotti
  • 995
  • 10
  • 13
  • The array is fetched from a database stored in html.I used ckeditor for storing textarea forms. – loksan May 27 '20 at 13:19