Reputation: 681
I saw the tag <%=j some-variable %>
in a ruby view file and I was wondering if anyone could tell me what the j
in it stands for? I know <%= %>
is used to print out ruby and <% %>
is for using ruby code in a view.
Upvotes: 0
Views: 741
Reputation: 3459
In Ruby on Rails views, j()
is an alias for escape_javascript()
:
Escapes carriage returns and single and double quotes for JavaScript segments.
This is usually used in DOM manipulation, when you want to render another ERB template and use that output as a parameter to your JS function, for example.
If you are using jQuery, you might have something like this in your JS response after creating a new record:
$('ul#items').append('<%= j render(resource) %>');
This would render the corresponding partial for the resource, escape the result such that it can be used as a Javascript string, enclose that escaped string in quotation marks, and then append that final string to a DOM node.
Update:
(This is derived from my comment in discussion for one of the other answers.)
A lot of Ruby developers write the j
right next to the <%=
, without any separating whitespace. Some write <%=j render 'something' %>
while it is common to enclose at least the inner method call arguments like this: puts some_method('bar')
.
It was the same story with the h
alias for escaping HTML before Rails started auto-escaping strings.
Upvotes: 6
Reputation: 10997
I'm pretty sure this is shorthand for escape_javascript
<%=j some-variable %> => <%= escape_javascript some-variable %>
will try to find a source for this
here's the source. Note that this is only available in Rails 4.0.
So i'm not sure, actually - the context in the docs makes it seem like it needs to be used in connection with render
...
$('some_element').replaceWith('<%=j render 'some/element_template' %>');
Upvotes: 3
Reputation: 51151
In this example, j
is method and some-variable
is its parameter.
After method is called, the result of this call is converted to string and inserted into your view.
To be more precise, j
is alias to escape_javascript
method, that escapes JavaScript characters.
Upvotes: 2