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.
Related
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.
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') { %>
I am having some trouble when printing javascript code that is created on the server side. The code must be placed in my html, but asp always escapes the string in such a way that my javscript doesn't execute. Here is my code:
//file "generateCode.ascx"
<%
if (Model.Overrides != null) {
if (Model.Overrides.JavascriptAposTabela != null) {
%>
<%: Model.Overrides.JavascriptAposTabela; %>
<%
}
}
%>
Am example of the result of the code above is:
function getGreenToRed(percent){
r = percent<50 ? 255 : Math.floor(255-(percent*2-100)*255/100);
g = percent>50 ? 255 : Math.floor((percent*2)*255/100);
return "rgb("+r+","+g+",0)";
}
$(".colormeter").css("background-color", getGreenToRed($(this).text()));
This is not the expected result.
I tried the solution proposed in these threads, but it did not work for me:
How do I prevent MVC3 html escaping my validation messages?
Stop the tag builder escaping single quotes ASP.NET MVC 2
I am using asp.net mvc 2
Well. Unfortunately, it was only ignorance of my part.
The solution is pretty simple:
//file "generateCode.ascx"
<%
if (Model.Overrides != null) {
if (Model.Overrides.JavascriptAposTabela != null) {
%>
<%= Model.Overrides.JavascriptAposTabela; %>
<%
}
}
%>
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).
Using Rails 3: In my update.js.erb file I found I was repeating a lot of stuff. So I tried to put it all into a helper. But I'm having trouble getting the helper to give back clean javascript. It puts in \" everywhere instead of "
Here's what I started with:
<% if #list.show_today %>
$("#show_today_check_<%= #list.id %>").removeClass("gray").addClass("orange").attr("value","0");
<% else %>
$("#show_today_check_<%= #list.id %>").removeClass("orange").addClass("gray").attr("value","1");
<% end %>
<% if #list.show_inventory %>
$("#show_inventory_check_<%= #list.id %>").removeClass("gray").addClass("white").attr("value","0");
<% else %>
$("#show_inventory_check_<%= #list.id %>").removeClass("white").addClass("gray").attr("value","1");
<% end %>
etc.
Here's the helper I wrote to generate the above javascript:
def toggelButtonState( object, name, color)
if object.send(name)
#add_col = color
#rem_col = 'gray'
#value = "0"
else
#add_col = 'gray'
#rem_col = color
#value = "1"
end
js = '$("#'
js += "#{name}_check_#{#list.id}"
js += '").removeClass("'
js += #rem_col
js += '").addClass("'
js += #add_col
js += '").attr("value","'
js += #value
js += '");'
end
I call it with:
<%= toggelButtonState( #list , 'show_today', 'orange' ) %>
And here's what I get in the response:
$(\"#show_today_check_2\").removeClass(\"orange\").addClass(\"gray\").attr(\"value\",\"1\");
Now I did notice a similar problem with straight html in helpers. It wouldn't let me return stuff in angle brackets. But then I found out about content_tag. Is there something similar for javascript? How can I get rid of the \"s?
Add
js.html_safe
as last line of toggelButtonState function