CoffeeScript in Rails does not correctly render partial - ruby-on-rails

$('#some').append('<%= render 'my_partial' %>')
And it renders it as text. It always escapes html. I have tried in all ways to avoid escaping.
$('#some').append('<%= j render('my_partial') %>')
$('#some').append('<%= raw render('my_partial') %>')
Result is the same.

If you want your coffee (or any files) to be interpreted as ERB, then you need to append the file name with .erb ie app.coffee.erb.
But a better question is why? Doing so will tightly couple your coffee to both rails and ruby making re-use much harder - much like putting css inline in HTML.
There are two better options IMO:
Use data attributes in HTML and access them with javascript
If you only have a single variable to pass, try something like <%= javascript_tag "my_func(#{#my_var})" %>. This will invoke a javascript function with that variable.

Related

Slim templates, format.js template rendering in Rails 4

I've always worked in ERB and made heavy use of .js.erb files to render JS responses. I've recently fallen for Slim templates but I'm having a difficult time finding an equivalent to this that keeps files in the Slim format.
Assuming I'm executing the update action within my controller and the end looks like this:
respond_to do |format|
format.js {}
end
And let's pretend that I'm trying to just send alert('hello') as a response.
update.js works correctly and so does update.js.erb, naturally. If update.js.slim looks like this:
javascript:
alert('hello')
...it is sent as a response that looks like this:
<script type="text/javascript">(function() {
alert('hello');
}).call(this);
</script>
That won't work because the browser expects Javascript and that is an HTML file with script tags. Thanks, Slim. It DOES work if I use | to render plain text:
update.js.slim
|
alert('hi');
Everything after the pipe character shows up in SublimeText 2 color-coded and I still get access to Ruby code and variables within #{}. So far, this seems like my best and only option if I want to insist on keeping things in Slim format, but since it doesn't give me any of the benefits of Slim, I almost feel like just using .js.erb for these files might be better, since it has native support for this sort of thing.
Is there a better way of doing it?

Is there an advantage to using link_to over the anchor tag in Rails?

Don't these two do the same thing?
<%= link_to "Example", '#', class: "somestyle" %>
Example
If I'm writing a static .html.erb page, if everything else is written with HTML tags, doesn't it make sense to use HTML tags for links as well? I'm not sure why one should use a helper. Similarly, for linking style sheets, javascripts, etc.
For the link tags, it may not make a difference which way you go. Unless you're linking to more than "#". For instance, using a routed path.
For the stylesheets and javascript, I think you will need to continue to use the Rails helpers if you're taking advantage of the asset pipeline. If so, the hash in the filename changes at each asset compilation (I believe), and manually trying to edit the filename each time could become a pain.

Moving unobtrusive javascript out of html.erb file

I have a html.erb file in one of my views. The file is pretty big and has about 2/3 javascript code and just 1/3 html. I dont like this file being too cluttered. The javascript part is mostly event handlers and usage of jquery UI components like date pickers, dialogs etc for the corresponding html elements in the page. I would like to separate the javascript part from the html part.
Can I move the javascript to a separate js.erb file and use it like a partial? What is the advantage of this?
How would I move the javascript to a static .js file when I use rails API like I18n.() and <%= form_authenticity_token %>. Should I pass them every time to the wrapping javascript function? Is there a better way to do this?
If I move javascript out of the html.erb file will it help in caching/rendering of html.erb page?
Interested to find out if there are any re-usable patterns
Sample code on the html.erb file:
<% content_for :javascript do %>
<script type="text/javascript">
$(document).ready(function()
{
$('#create_segment_dialog').dialog({
title: "<%= I18n.t("segment.create_segment_title") %>",
// lots of javascript
}
</script>
<%end %>
//HTML starts here
<div id="right-column">
My 2c, but I know there are differing opinions on this:
Try and separate out as much of your JS code into a function or functions and put them into JS files in your asset pipeline. Take advantage of the move to break your JS into re-usable components that could be used by other methods/controllers.
This means you get all the benefits of the asset pipeline for the JS you move there:
Caching & fingerprinting your JS assets
Minification & compression support to save bandwidth
Minification to obfuscate your code if that is something you want
Concatenation of JS files to reduce the number of requests a browser has to make
Possibility to serve the assets from another location (CDN, web tier vs app tier)
Improved DRYness if that JavaScript is used by other methods/controllers
The drawback? As you've pointed out, any Rails variables have to be passed in as parameters to the functions.
Moving your JavaScript to a .js.erb partial is an option, but if this code is very specific to a particular method or controller then it is not necessarily improving DRYness - it may make your code a little more readable, by separating HTML and JS.

Rails with backbone-rails: asset helpers (image_path) in EJS files

I have a Rails 3.1 app that uses the codebrew/backbone-rails. In a .jst.ejs template, I would like to include an image, like so:
<img src="<%= image_path("foo.png") %>"/>
But of course the asset helpers are not available in JavaScript.
Chaining ERB (.jst.ejs.erb) does not work, because the EJS syntax conflicts with ERB.
Here is what I know:
The asset helpers are not available in the browser, so I need to run them on the server side.
I can work around the problem by making the server dump various asset paths into the HTML (through data attributes or <script> and JSON) and reading them back in JS, but this seems rather kludgy.
Is there a way to somehow use the asset helpers in EJS files?
There is a way, actually, to chain a .jst.ejs.erb file, although it's fairly undocumented, and I only found it through looking at the EJS test cases. You can tell EJS to use {{ }} (or [% %] or whatever else you want) instead of <% %>, and then ERB won't try to evaluate your EJS calls.
Make sure to require EJS somewhere in your code (I just included gem 'ejs' in my Gemfile), and then create an initializer (I called it ejs.rb) that includes the following:
EJS.evaluation_pattern = /\{\{([\s\S]+?)\}\}/
EJS.interpolation_pattern = /\{\{=([\s\S]+?)\}\}/
Then just make sure to rename your templates to .jst.ejs.erb, and replace your existing <% %> EJS-interpreted code with {{ }}. If you want to use something other than {{ }}, change the regular expressions in the initializer.
I wish there were an option in Sprockets to handle this through the config rather than having to explicitly include EJS, but as of the moment, there's no way to do that that I know of.
I can see two ways. Neither are great.
When you say <%%= variable %> then this is rendered by ERB as <%= variable %>, so you could double percent escape everything but the asset_tags and that would survive the trip through one ERB pass on the way to EJS.
If you find that too gross...
How about making a different javascript file, with an ERB extension, that defines your asset paths? And then use the asset pipeline to require that.
So say assets.js.erb defines something like:
MyAssets = {
'foo': <%= image_path("foo.png") %>,
...
}
And then require this somewhere near the top of your manifest. And then reference the globals however that works in EJS.
For those willing to try HAML instead of EJS: Using haml-coffee through haml_coffee_assets has worked well for me as well.
You can have the following in a .hamlc.erb file:
%img(src="<%= image_path('foo.png') %>")
(It still doesn't give you routing helpers though, only asset helpers.)
Ryan Fitzgerald was kind enough to post a gist of his JavaScript asset helpers (which get precompiled with ERB): https://gist.github.com/1406349
You can use corresponding Javascript helper via the following gem:
https://github.com/kavkaz/js_assets
Finally (after installing and configuring) you will be able to use it like this:
<img src="<%= asset_path("foo.png") %>"/>

Rails 4: using a js.erb file as a partial

Is it possible to define a .js.erb file as a partial? I have several .js.erb that have code that could just be moved to a common file like a partial, and then I would just call render on it.
How can I do this?
Same rules as normal partials: name the file beginning with _yourfile.js.erb and in your main file call it with <%= render partial: "yourjsfile" %>
Although, being javascript a programming language, you might want to think to refactor your code instead of resorting to this

Resources