Write ejs variable in jQuery

Viewed 2326

I am appending some html to a div using jQuery:

public/js/writeInputs.js

$("#myDiv").append("<input type='search' value='<%= filters.title %>' name='filters[title]' class='form-control'>")

In this case filters is an object that I'm passing from my node express backend, the value of which I want to display in my input. However, the above renders the ejs variable as the string literal:

<%= filters.title %>

If I hardcode this value into the html it works as expected:

views/partials/inputs.ejs

<input type="search" name="filters[title]" value="<%= filters.title %>" class="form-control">

How can I write an ejs variable in jQuery?

I've tried these approaches in my append, but none work:

value="<%= filters.title %>"
value=${<%= filters.title %>}
value='"<%= filters.title %>"'
3 Answers

Node express first renders HTML and then browser do some requests based on HTML to get scripts, images, etc. For this reason <%= filters.title %> is not interpreted by EJS.

As an alternative render some data into HTML and rewrite JavaScript to read filters.title from HTML, like this:

<input type="hidden" id="filter" value="<%= filters.title %>" />

<script src="yourScript.js"></script>

yourScript.js:

    var filter = document.getElementById("filter").value;
    $("#myDiv").append("<input type='search' value='" + filter + "' name='filters[title]' class='form-control'>");

Only ejs files inside your views folder are rendered from the server so you will have to create the variable in that file instead. Here is an example:

view.ejs

<script>
    var ejsVal = <%= val %>; // You have to use var to make it global
</script>
<script src="script.js"></script>

script.js

console.log(ejsVal);

can you try like this?

var temp = <%= test  %>;
$("#myDiv").append("<input type='search' value='"+temp+"' name='filters[title]' class='form-control'>");
Related