Passing Params to nodejs ejs template - javascript

Guys i'm trying to render MongoDB record in my .ejs file, however, i console.log the variable prior the end of my route and i get the expected value, however, if becomes undefined in the .ejs file
below is the code:
router.get("/new",function(req,res){
var selectedMake;
console.log("Welcome to new make route!");
Make.find({},function(err,result){
if(err){
console.log("an error occured while fetching the data");
}else{
if(req.query.id){
Make.findById(req.query.id,function(err,foundMake){
console.log("found the query string");
selectedMake = foundMake;
console.log(selectedMake); // renders expected value when passing valid ID in the query string
})
}
res.render("vehicles/newvehiclemake",{selectedMake: selectedMake, makes:result,modelId: req.query.id});
}
})
});
and here is the .ejs excerpt where the variable selectedMake is being used:
<% if (!typeof selectedMake == undefined) { %>
<% selectedMake.models.forEach(function(model){ %>
<tr><td><%= model.name %></td></tr>
<% }) %>
<% }else { %>
<tr><td>No Models available for the selected Make</td></tr>
<% } %>
appreciate your input and thanks in advance.

typeof on any variable returns a string so you have to check for 'undefined' in your ejs
<% if (typeof selectedMake !== 'undefined') { %>

I'm not sure but you make mistake at first line in your .ejs file.
Try this:
<% if (typeof selectedMake !== 'undefined') { %>

Related

Working with JSON.stringify( obj ) in node/express ejs

I'm trying to pass an object to my view using JSON.stringify but I am not sure how to access elements in the object. Here is how I pass the object to my view:
const getTracking = (request, response) => {
pool.query('SELECT * FROM tracking', (error, results) => {
if (error) {
throw error
}
var trackingObj = JSON.stringify(results.rows);
response.render('pages/trackingInfo', {
trackingObj: trackingObj
});
})
}
Then in my index.ejs document I can access my object like so:
<p><%= trackingObj %></p>
which results in the following output in the browser (data is grabbed from postgres database):
[{"wo_num":1,"completion_date":"2021-08-04T04:00:00.000Z","material":"test","description":"test","qty":1,"total_hours":null},
{"wo_num":2,"completion_date":"2021-08-05T04:00:00.000Z","material":"test2","description":"test2","qty":2,"total_hours":2},
Is there a way to access the elements of this JSON.stringify object individually so I could do something like display them in a table?
JSON.parse('<%- JSON.stringify(trackingObj) %>')
if you want to just see the content you can also use (will be displayed on the terminal
<% console.log(trackingObj) %>
for a better view :
<% console.table(trackingObj) %>
As #Jayesh commented, the solution was to access the object using indices like so: trackingObj[0].material
To then display the elements in a table you can iterate through them in the following manner:
<% trackingObj.forEach(function(obj) { %>
<tr>
<td> <%= obj.material %> </td>
<td> <%= obj.wo_num %> </td>
<tr>
<% } %>

Append ruby partial in javascript, and pass a rails variable

Creating a chat component with ActionCable in Rails5. I learned today that render partial, even in .js.erb does supposedly doesn't work. render specifically is the issue. So now I'm trying to call a partial, and pass a ruby variable to it.
I have tried many things, currently this is how I'm trying to accomplish it:
chatbox.append(<%= j (Erubis::Eruby.new(File.read(File.join(Rails.root, 'app/views/msgs',
'_msg.html.erb'))).result(msg: #msg)) %>);
and the error is
undefined method `self_or_other' for #<Erubis::Eruby:0x007f832bbb8590>
So the partial is there, but the variable is not correct.
views/msgs/_msg.html.erb
<li class="<%= self_or_other(msg) %>">
<div class="avatar">
<%# if msg_interlocutor(msg).avatar.url(:thumb) == "thumb/missing.png" %>
<%= image_tag(msg_interlocutor(msg).avatar.url(:thumb), class: "convoPic")%>
</div>
</li>
I also tried:
chatbox.append(<%= j (Msg.new(File.read(File.join(Rails.root, 'app/views/msgs',
'_msg.html.erb'))).result(msg: #msg)) %>);
And get this error:
When assigning attributes, you must pass a hash as an argument.
Trying with render:
App.msgs = App.cable.subscriptions.create('MsgsChannel', {
received: function(data) {
var chatbox = "#chatbox_" + data.convo + " .chatboxcontent"
var id = data.convo;
var sender_id = data.user.id;
var reciever_id = data.receiver;
<%= #msg %> = data.msg
$(chatbox).append("<%= escape_javascript render(:partial => 'msgs/msg', :locals => { :msg => #msg }) %>");
chatbox.scrollTop(chatbox[0].scrollHeight);
},
renderMsg: function(data) {
console.log(data)
}
});
And error I receive:
undefined method `render' for #<#<Class:0x007fe976b5c180>:0x007fe9773ed470>
How do I properly call in a partial, pass it a ruby variable (with the msg record). Thank you!!
do you have a "messages_helper.rb" file with the following
module MessagesHelper
def self_or_other(message)
message.user == current_user ? "self" : "other"
end
def message_interlocutor(message)
message.user == message.conversation.sender ? message.conversation.sender : message.conversation.recipient
end
end
This is where it's defined.

How to use if condition in ejs template

Server Code
Details['11'] = {
'id': '11',
'name': 'Avanish'
};
res.render('/index',{'Message': Details});
Page code
<script>
var ERRORCONST = 'Error';
var NORECORDS = 'No records';
</script>
<%if(Message != undefined && Message != NORECORDS && Message != ERRORCONST ){%>
<%Message.forEach(function(key){%>
<span><%= key.id %> - <%= key.name %></span>
<%});%>
<%}%>
Getting error NORECORDS is not definedand print all code on page.
I have two error. One is how to use Multiple condition in single if statement and second is how to compare javascript varibale with server variable
<% var ERRORCONST = 'Error';
var NORECORDS = 'No records'; %>
In ejs template please use constant like this.
You can not compare ejs variable and local script variable.

EJS failing to render template

I'm trying to render a template which includes this block of code:
<% if(type === 'Not Within Specifications'){ %>
<% if(Length !== undefined) { %><h5>Length: <%= Length %> </h5> <% } %>
<% if(Width !== undefined) { %><h5>Width: <%= Width %> </h5> <% } %>
<% if(thickness !== undefined) { %><h5>Thickness: <%= thickness %> </h5> <% } %>
<% } %>
However when the template attempts to render, it throws and error that a variable is "undefined" if one of the above variables is in fact undefined.
The point of the if statements catching undefined variables was to eliminate this error from happening, however it seems that the error is still being thrown even when i'm checking to see if the variable is undefined. Does anyone know why this might be? Thanks so much!
You need to use typeof:
<% if(type === 'Not Within Specifications'){ %>
<% if(typeof Length !== 'undefined') { %><h5>Length: <%= Length %> </h5> <% } %>
<% if(typeof Width !== 'undefined') { %><h5>Width: <%= Width %> </h5> <% } %>
<% if(typeof thickness !== 'undefined') { %><h5>Thickness: <%= thickness %> </h5> <% } %>
<% } %>
Also, see this related question: How would you check for undefined property in ejs for node.js?

Outputting directly to template with Embedded Javascript Syntax

I'm using Backbone with Underscore templates. I have a JavaScript if() condition in my code that looks something like this:
<div class='faces'>
<% if(somevalue === true) { %>
your face
<% } else { %>
my face
<% } %>
</div>
However I find this syntax awkward and I really would like to use something like the following, even though it doesn't actually work (replaces entire document with the text):
<div class='faces'>
<% if(somevalue === true) {
document.write("your face");
} else {
document.write("my face");
}
</div>
I want the string to be output in the template exactly where it is called. For outputting a simple variable EJS (and underscore) have a great syntax of
<%= somevalue %>
Where the = is the critical part that document.write()s it out into the template. Is what I'm trying to accomplish possible? Can JavaScript output inline?
There are a few options, you could use <%= %> and a ternary:
<%= somevalue == true ? 'your face' : 'my face' %>
or you could use print:
You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.
var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge."
so you could do this:
<% if(somevalue == true) {
print("your face");
} else {
print("my face");
} %>
I'm assuming that if(somevalue = true) is a typo and should be if(somevalue == true).

Categories

Resources