rendering a html.erb in rails with javascript - javascript

I create a page and some parts of it are layout files that are rendered. However I want to render one of these rendered part again with javascript code.
I want to render these part again
<div id="dialog" title="Bookmark Folders" style="resize: both;">
<%=render "layouts/filetree.html.erb"%>
</div>
It render function creates this:
<div id="accordion">
<% #user.folders.each do |f| %> <h3 id="<%= f.folder_name%>" class="folderBar"><b id="folderName"><%= f.folder_name%></b> created <%=distance_of_time_in_words(f.created_at, Time.now)%> before</h3>
<div class="<%= f.folder_name.delete(" ")%>">
<%if f.docs.empty?%>
<b>-No document currently!-</b>
<%else%>
<% f.docs.each do |r|%>
<%= r.title%><br/>
<b><%=r.url%></b><br />
<%= r.snippet%><hr/>
<%end%>
<%end%>
</div>
<%end%>
</div>
Because after some execution there are some changes over "folders", I want to render this part again to see the update.

You shouldn't attempt to render erb with javascript - it's not how it's done (not to mention you'd have to write yourself a erb parser and eventually call the server for data anyway).
If on the other hand, you're asking how to issue the render of some template using Javasript and then replace old content with new one then...
Watch this http://railscasts.com/episodes/205-unobtrusive-javascript,
read this Rails 3 and RJS to get the idea of how to trigger some content updates via javascript.
General idea is
Render the initial full page
Trigger ajax call (either after some time or by manual user request) to do a request to your rails application
Handle that request and respond to it with javascript script (the script content should contain all the functionality and content to replace what you want)

It's possible to share templates between the server and the client. One library that allows for this is called mustache.
But if this is the only case you need it I'd go with the RJS approach as well.

Instead of rendering I did it AJAX way and update it on the page. Thanks for the answers but I did not use any of these.

Related

How to render ejs variable as HTML using <script>

I'm making a simple blog project and I came up to this problem.
I'm using EJS and I'm trying to render variable as HTML using tag
What I tried:
<div class="container-fluid">
<script>
document.write(<%= content %>)
</script>
</div>
I thought this would work but it doesn't show
anything at all, if I type <p><%= content %></p> it shows it as words, not HTML.

How can I add javascript to only a single view in Rails 5?

I have a single controller that has 2 actions/views and a channel all of which have been scaffolded and pretty much using a default project.
When I load either view I can see that the channel subscribes properly.
I need the subscription to happen only on one of the views. Currently the asset pipeline appears to be compiling everything into a single js file and then serving that js file to every page.
When I scaffolded my channel it created some javascript called channel.js. How can I include channel.js with only specific actions/views?
The asset pipeline indeed compiles everything into a single JS file, so there is no built-in way to limit the execution of certain JavaScript files to specific actions.
There is a way to solve this, however. First, add this helper method to application_helper.rb:
# application_helper.rb
def body_classes(*args)
return (#body_classes || []).join(" ") if args.empty?
#body_classes ||= []
#body_classes += args.map { |klass| klass.to_s.gsub("_", "-") }
#body_classes.uniq!
nil
end
And use it in your layout:
<!-- application.html.erb -->
<body class="<%= body_classes %>">
<!-- ... -->
</body>
With this, you can specify certain body classes in your templates, to be added to the <body> tag:
<!-- your_action.html.erb -->
<%= body_classes :my_custom, :action_class %>
<h1>Your action</h1>
<!-- ... -->
The code above will add the following classes to <body>:
<body class="my-custom action-class">
Finally, you can test for these body classes in your JS code:
// your_action.js
if($("body").hasClass("my-custom")) {
// run code specific to pages with the 'my-custom' class
}
Try going into your controller that holds the method to the view you want to have the javascript incorporated in and write this inside:
def 'the view you want to effect' # This could be "index" for your index.html.erb view
#java = "channel.js"
end
Then in the following file, locate your <%= javascript_include_tag %>
views > layout > application.html.erb
Include this into your tag to load a different javascript file for any view you want with the previous process. (Try it with CSS inside your CSS include tags too.)
<%= javascript_include_tag '#{#java}' %>

rails render view onclick with javascript

I'm trying to create a view, where users can click on different buttons and render different content based on the buttons they click. I've tried getting this done with JS but can't really get it to work. I made a button in my view:
<div class="link">
<%= link_to "Greetings", "#" %>
</div>
<div id="show"></div>
then in job.js.erb:
$(function() {
$('.link').click(function() {
$('#show').append("<%=escape_javascript render(:partial => 'show' %>");
});
});
unfortunately render is not supported in assets, but I don't really know what the best way is to make this happen.
One way you can try is to let the button click go to a controller action, by AJAX, and then render the file with name <action_name>.js.erb. this file will then be able to call the render action.
I will expatiate more with the following:
Assuming the resource in question is Greetings and you have a dynamic_show action in the Greetings controller, for example, and you have a dynamic_show_greetings_path routing to this action.
From inside your view, you can have:
<div class="link">
<%= link_to "Greetings", dynamic_show_greetings_path, remote: true %>
</div>
<div id="show"></div>
and the Greetings#dynamic_show action will be like follow:
def dynamic_show
respond_to do |format|
format.js
end
end
then, in your view directory, you have a dynamic_show.js.erb file, which will contain the script to append the dynamic view as follow:
$('#show').html("<%=escape_javascript render(:partial => 'show') %>");
And that solves it for you!
Of course, to now make it dynamic, you have to then pass in params to the controller, and then render content based on the response gotten.
PS:
setting remote: true on the link ensures that the call will be an AJAX call.
controller actions by default renders the file with same name as the action name, therefore, dynamic_show responding to js will render dynamic_show.js.erb
Hope this throws a great light into it for you... ;)
It sounds like you need jQuery for this.
You can wrap the rendered partial in a parent div with a hide class. When the button is clicked toggle displaying the content.
http://api.jquery.com/show/
$('#your-button').click(function(e){
$('.hidden-div').toggleClass('hide');
});
There are two ways to do this.
Firstly, if you're wanting to load the JS on-page, you need to use what #anchalee suggested, and preload the content with some sort of "hide" class in the CSS:
#app/assets/javascripts/application.js
$(document).on("click", "a.hidden", function(e){
e.preventDefault();
el = $(this).attr("href");
$(el).toggle();
});
#app/views/controller/your_view.html.erb
<%= link_to "User", "#user", class: "hidden" %>
<div id="user" class="hidden">
Hello
</div>
This will take any divs with the id specified by the href attribute of the link, and then make it so that the div will hide or show depending on its current state.
--
Secondly, you have the off-page method (using ajax).
This is used to get data from the server, and will be where you'd load server-centric data such as what you're trying to do now.
Doing this is actually quite simple:
#app/controllers/your_controller.rb
class YourController < ApplicationController
layout: Proc.new{|c| !c.request.xhr? }
end
This will return any data you need without the layout:
#app/assets/javascripts/application.js
$(document).on("click", "#show", function(e){
e.preventDefault();
$.get($(this).attr("href"), function(data){
$("#show").html(data);
});
});
#app/views/your_controller/show.html.erb
<%= link_to "Show", [[url for page]], id: "show" %>

How to properly render a partial template that is using a jQuery plugin?

I am using Ruby on Rails 3.2.2 and the jquery-rails 2.0.2 gem (including the jQuery UI plugin). In order to DRY (Don't Repeat Yourself) my code I am planning to "extract" the jQuery Dialog Widget in a partial template that will be rendered in my application almost the same way; so, I am thinking to implement and render that template by passing some "complex" code (possibly, JavaScript code) throughout the :locals statement... but I have some trouble on how to properly pass that code.
Specifically, I would like to render the template by passing :locals with which "build" / that "populate" some jQuery Dialog Option, Event, Method (see the jQuery UI Official Documentation for more information) as-like, for example, the option title or the event close (note: it is intended that the "passed" / "builded" / "populated" content is JavaScript code or both JavaScript and Ruby code).
What / how could / should I make to accomplish what I aim to make? Is there some "common" approach or practice?
Here's a simple example. See if this is helpful, and YMMV.
A partial can contain JavaScript and Ruby code as ERB (or HAML, or whatever templating you want to use).
I use the convention of putting shared partials in the directory ./app/views/shared.
Example file ./app/views/shared/_dialog.html.erb:
<!-- typical jQuery dialog box creator -->
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
<!-- typical dialog with Ruby ERB for title and message -->
<div id="dialog" title="<%= title %>">
<p><%= message %></p>
</div>
To call the partial from your view page:
<h1>My Page</h1>
<%= render :partial => "shared/dialog",
:locals => { :title => :"Hello", :message => "World" } %>

Removing :notice and <div> in Rails 3.1 app on page refresh

This might be an easy one for you guys, but I'm not sure the best way to achieve it.
Is there some type of .erb I can write that asks "If :notice is present, then render..."?
Here's more about the issue:
My controller specifies a :notice for both the create and update actions (pretty standard). When I load the pages, the notices do as I'd expect and show up. When I reload the page however, (not sure why someone would do this, but I did), the :notice goes away (great, that's what I want), but the containing <div> remains.
How do I go about ensuring that the encapsulating <div> is removed along with the :notice? I'm not sure what conditionals to specify in my view or maybe controller. The view looks something like this (btw, I'm using Twitter Bootstrap JS alerts).
View
<div class="alert-message success fade in" data-alert="alert">
<a class="close" href"#">×</a>
<p><%= notice %></p>
</div>
My controller is a single scaffolded model/resource with basic structure
What I did was:
<% if notice == "[:notice string]" %>
.
.
.
<% end %>
Not sure if this is the most efficient and "Rails-y" way to do it, but it worked for me.

Categories

Resources