Outputting directly to template with Embedded Javascript Syntax - javascript

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).

Related

Passing Params to nodejs ejs template

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

How to break a loop with the EJS template language?

I am developping a simple web application with sails.js.
In my frontend code, i'm looping over an array of objects sent by the controller, and i am searching for a specific object. I'd like to break the loop once the object has been found. Is there a clean way to do that using the ejs template language ?
I coulnd't find anything about it on the EJS official website, nor on sails website.
I naively tried this until now :
<% objects.forEach(function(object) { %>
<% if(object.someId == someValue) {%>
<%= object.name %>
<% break %> <!-- This raise an illegal statement exception -->
<% } %>
<% } %>
The following code works as expected, but i'm looking for a cleaner solution if any
<% var found = false %>
<% objects.forEach(function(object) { %>
<% if(object.someId == someValue && !found) {%>
<%= object.name %>
<% found = true %>
<% } %>
<% } %>
It's not an EJS-related question.
break statement terminates the current loop. While you are not inside a loop. You are inside callback function, that's called by forEach method once per array element. There's no ability to interrupt forEach (see How to short circuit Array.forEach like calling break?). But, if you need it, you may use for loop for a clean solution:
<% for (var l = objects.length, i = 0; i < l; i++) { %>
<% object = objects[i]%>
<% if(object.someId == someValue) {%>
<%= object.name %>
<% break %> <!-- This will work as expected -->
<% } %>
<% } %>

Render simple form partial in Rails/Javascript

I want to render my form partial in javascript erb file. When I place it in there it gives me a no method error. Any ideas?
script.js.erb
$(document).ready(function() {
$(".enquiry-button").click(function(e) {
e.preventDefault();
e.stopPropagation();
if ($(this).parents('.cell').find('form').length == 0) {
$(this).closest('.cell').append(
"<div class='enquiry-form'>" +
"<%= escape_javascript( render '/static/form' ) %>" +
"</div>");
$(this).closest('.cell').find(".enquiry-form:last").slideDown("slow");
} else {
$(this).closest('.cell').find(".enquiry-form:last").slideToggle("fast");
}
});
});
_form.html.erb
<%= simple_form_for #user do |f| %>
<%= f.error_messages %>
<%= f.input :email %>
<%= f.button :submit %>
<% end %>
error
NoMethodError in Static#home
Showing /Users/colton/kitchen_ninja/kitchen_ninja/app/views/layouts/application.html.erb where line #6 raised:
undefined method `render' for #<#<Class:0x007f90cc875c80>:0x007f90cd2017e0>
(in /Users/colton/kitchen_ninja/kitchen_ninja/app/assets/javascripts/script.js.erb)
Extracted source (around line #6):
You are mixing two separate things together. Your render needs to run on the server. JavaScript's job is just to make an AJAX request and get a resource.
So, supposed you were to to this:
$.ajax(url: "/test").done(function(html) {
$("#results").append(html);
});
AJAX's only role is to grab a remote resource and parse the results.
In Ruby, you can use render to emit the HTML:
<%= escape_javascript( render '/static/form' ) %>
Just make sure you point the AJAX request to the right resource so Ruby can do the rest of the magic.
Since you are pre-processing the script with .erb, you could use Ruby's string interpolation to return the partial as a string literal in the JavaScript file.
html = "<div class='enquiry-form'>" +
"#{j render partial: 'static/form'}}" +
"</div>"
$(this).closest('.cell').append( html );

prevent javascript code escaping in asp.net

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; %>
<%
}
}
%>

how to return clean javascript from a rails3 custom view helper?

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

Categories

Resources