Rails - how to insert/render a file inside a View - ruby-on-rails

in index.html.erb, I would like to know how to insert index.js.erb, something like:
<script type="text/javascript">
$(function() {
<%= render =>"home/index.js.erb" %>
});
</script>
Any ideas on how to just insert the index.js.erb file ?
thanks

<%= File.read "#{RAILS_ROOT}/app/views/home/index.js.erb" %>

Set your file as a partial and append preprend or do what you wana do with it.
For a partial file named _index.js.erb located in the same folder of where the file with this code is called will be prepend in the DOMID exemple.
jQuery('#exemple').prepend("<%= escape_javascript(render(:partial => 'index')) %>");
Maybe you can do a html file with it...
<% javascript_tag do %>
<%= render :partial => 'index' %>
or direct code
<% end %>

Related

Load Rails partial with passed values using AJAX?

In my Rails app users have folders, and inside these folders are posts that they can add. Right now I have the folders displaying in my view like this:
<% current_user.folders.each do |folder| %>
<a href='#' id="addSubmissions">
<div id="post-container">
<%= folder.title %> <p id="created-time">Created <%= folder.created_at.strftime("%e/%-m") %></p>
</div>
</a>
<% end %>
What I'd like to do is load the submissions associated with a folder into a div when the #addSubmissions link is clicked. I've tried testing it out with this:
$('#addSubmissions').click(function(){
$('#post-container').append('<%= render :partial => 'contents', :locals => {:folder => folder } %>');
});
But it seems like that render code actually needs to be local beforehand.
The _contents.html.erb partial works, and is pretty simple:
<%= folder.title %>
<% folder.submissions.each do |i| %>
<%= i.title %>
<% end %>
How could I go about doing this? Again, I want to be able to click the link of a folder and load the submissions inside the folder into a div in the view. I'm thinking AJAX might be the solution, but I'm pretty new to Ruby so I don't know how to implement this.
This way it won't work. You need contoller method, which responds to JS, because you are fetching pure ruby variables.
Instead of:
<a href='#' id="addSubmissions">
you might try:
<%= link_to folder_content_path(folder), :remote=>true, :class=> "addSubmissions", :id=>folder.title %>
<div class="post-container" id="<%= folder.title %>">
<%= folder.title %> <p id="created-time">Created <%= folder.created_at.strftime("%e/%-m") %></p>
</div>
or other method name you want. Also note, that ID should be unique for page, otherwise you won't get expected result. Here I use folder name as ID, it probably unique, and it is easy way to find div we want modify with JS.
def folder_content
#folder=Folder.find(params[:id])
respond_to do |f|
f.js
end
end
folder_content.js.erb:
$("#"+"<%=#folder.title %>").append('<%= j render :partial => 'contents', :locals => {:folder => #folder } %>');

Render template having Jquery datatables in .js.erb file

I am currently working on a project where I am implementing several reports. The report filters are remotely submitted to my action and the return results are displayed in Datatable with searching,sorting and pagination.
I have a drg.js.erb file which is having code like this :
var html = "<%= escape_javascript(render(partial: 'drg_datatable',formats: [:html],locals: {result: #result})) %>";
$("#datatable-result").append(html);
The partial _drg_datatable.html.erb is having datatable implemented like this. Below is my _drg_datatable.html.erb file :
<% if result %>
<table id="results" class="table table-striped table-bordered display">
<% case params[:view] %>
<% when "ahfs" %>
<%= datatable_ahfs_result(result) %>
<% when "drg_code" %>
<%= datatable_drg_result(result) %>
<% when "inpharmics_id" %>
<%= datatable_inpharmics_id_result(result) %>
<% when "provider" %>
<%= datatable_provider_result(result) %>
<% else %>
<% end %>
</table>
<% end %>
The problem I am facing is that when I render the partial _drg_datatable.html.erb using .js.erb file it creates the table but escapes the javascript to add sorting,pagination and other cool features we get in Jquery Datatables. Can someone point me how should I go about doing this ? I have tried to render the partial is .js.erb without writing escape_javascript but then the partial does not get rendered at all.
You must explicitly call the datatable js function in your drg.js.erb in order to "datatablize" your table. Ex:
var html = "<%= escape_javascript(render(partial: 'drg_datatable',formats: [:html],locals: {result: #result})) %>";
$("#datatable-result").append(html);
$('#results').dataTable();
I suppose you have something like:
$(document).ready(function(){
$('a selector of yours').dataTable();
});
somewhere in your application's javascripts. This runs once, after document load and applies to elements existent to your dom. Since now you are adding a new table you have to "re assign" the datatable behavior...
#grotori: Your solution gave me a hint of fixing it. I renamed my datatable id with a name which was not used in the application anywhere. I removed the initial implementation of the datatable in the partial and modified the code to render the partial first and than apply datatable to it. Here is what I did :
var html = "<%= escape_javascript(render(partial: 'drg_datatable',formats: [:html],locals: {result: #result})) %>";
$("#datatable-result").html(html);
jQuery(function() {
$("#drg-results").dataTable({
"sDom": "<'row-fluid'<'span4'l><'span7 pull-right'f>r>t<'row-fluid'<'span4'i><'span7 pull-right'p>>",
"sPaginationType": "bootstrap",
"sScrollX": "100%",
"bDestroy": true,
"bProcessing": true,
"bScrollCollapse": true
});
});
Hope this helps other trying to achieve the same thing.

Render to partial by Ajax in Rails App

I have almost done! but I have an issue, in my Controller file have this:
def show
#user = User.find(params[:id])
#posts = #user.posts.paginate(page: params[:page])
end
Then I have this piece of code in my file show.html.erb:
<div class="span8">
<%= render 'follow_form' if signed_in? %>
<% if #user.posts.any? %>
<h3>Microposts (<%= #user.posts.count %>)</h3>
<div id='posts'>
<div class='page'>
<ol class="microposts">
<%= render #posts %>
</ol>
</div>
</div>
<% end %>
</div>
At the bottom of this file, I have a Javascript code that I have taken from the tutorial: https://github.com/amatsuda/kaminari/wiki/How-To:-Create-Infinite-Scrolling-with-jQuery
In the same folder I have the file index.js.erb with:
$("#articles").append("<div class='page'><%= escape_javascript(render(#users)) %></div>");
$("#posts").append("<div class='page'><%= escape_javascript(render(#posts)) %></div>");
In a partial _posts.html.erb have this:
<div class='article'>
<%= image_tag(user.picture_url, :width => 50) %>
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>
</div>
The first one already works in my file index.html.erb, the problem is with the second piece of code, when I try to render the partial at #post, It brings the follow log:
**
'nil' is not an ActiveModel-compatible object that returns a valid partial path.
Extracted source (around line #2):
1: $("#articles").append("<div class='page'><%= escape_javascript(render(#users)) %></div>");
2: $("#posts").append("<div class='page'><%= escape_javascript(render(#posts)) %></div>");
**
How can I render that partial?
Thanks a lot :D
I usually use the .js.erb template to render the partial into a var then set it on the page using JS. Be sure to escape_javascript the template content otherwise you will get JS errors.
<% template_html = render :partial => '_feed_item.html.erb' %>
<%="$('div#content').html('#{escape_javascript(template_html)}</div>');" %>
I think the above should work in erb. I use HAML so mine looks like:
-template_html = render :partial => 'partial_template'
!="$('div#content').html('#{escape_javascript(template_html)');"
Cheers.
Based on your In script I'm calling to /users?page=, and I was wondering that It may calls the line, you must make sure that your controller is populating the #posts variable if your view is using this. Can you show the controller method users?

interpreting coffeescript in a layout

I am adding some view specific .js code to the header of the page using content_for like so
<% content_for :head do %>
<script lang="text/javascript">
$.getJSON("<%= book_chapters_path(#book) %>", function(data){
});
</script>
<% end %>
now how would I switch that js code to coffescript, can I put in a code block to tell rails to convert it to javascript, or even just add "lang/coffeescript" and rails would then just handle it.
In layout:
<% content_for :head do %>
<%- javascript_tag do %>
<%= render :partial => "cs/coffee-partial" %>
<%- end %>
<%- end %>
Where cs/coffee-partial is a views/cs/_coffee-partial.html.coffee.
You can even pass local variables to render and output them into your coffee-partial:
<%= render :partial => "cs/coffee-partial", :locals => {:version => '0.1', :name => 'varName'} %>
And then:
lib =
version: '<%= version %>'
'<%= name %>': 'some value'
You can use this gem: https://github.com/markbates/coffeebeans

How to merge multiple partial templates into one file?

I'm using Ruby on Rails 3 to create my web app.
I don't want to create a template file for each tiny partial template so I tried to merge them into one file using content_for method but it doesn't works.
My ERB template files are as follows.
layout/_fragments.html.erb: contains contents of some partial templates
<% content_for :twitter_checkbox do -%>
<% can_post_twitter = current_user && current_user.twitter_oauth %>
<% label_text = can_post_twitter ? "Post to Twitter" : "Set up your Twitter account" %>
<%= label_tag :twitter, label_text %>
<%= check_box_tag :twitter, 0, false, :disabled => !can_post_twitter %>
<%- end %>
<% content_for :other_content_of_partial_template do -%> # content of another partial template
...
layouts/application.html.erb
<!DOCTYPE html>
<html>
...
<body>
<%= yield %>
</body>
</html>
<%= render 'layouts/fragments', :formats => :erb %>
layouts/_form.html.erb
<%= form_for(#entry) do |f| %>
...
<%= content_for :twitter_checkbox %> # it shows nothing
<% end %>
What is wrong with this way?
Are there any other better ways to write multiple partial templates into one file?
I suppose you have run the _form partial before your main layout had the chance to run the _fragments partial, so when you display the fragments, they are not yet created.
The action is rendered before the layout, not after. Calling the _fragments from your action instead of from layout should make it clear whether this is the problem. At least, I believe so ;-)
You're missing the = sign in the second snippet which would tell Rails to display the returned text.
<%= form_for(#entry) do |f| %>
...
<%= content_for :twitter_checkbox %> # Note <%= - it should now show stuff
<% end %>

Resources