I am new in ROR
I want integrate html code with ROR Code Like PHP
This is php Exmple code:-
$output='';
$output.='<div>how r you?</div>';
$output.='<div> fine</div>';
echo $output;
Output
how r you? fine
Help how to integrate html with ROR code? Like php see above the php code.
Use String#+, it's like PHP's . String operator:
output = "Hello"
output += " world!" # same as output = output + " world!"
Or use String#<<
output = "Hello"
output << " world!"
Which is the same as String#concat:
output = "Hello"
output.concat(" world")
The last two examples modify the contents of output.
You can use helpers to integrate html code with the ROR code.
In the helpers itself you can generate tags as <p> or <div> and close them after inserting the data from the back end
In short you can generate html pages dynamically in the helpers. Helpers are particularly for views
You can refer to the below link for more clarity
Using helpers in rails 3 to output html
In rails there is a available method called html_safe(). You can use this to integrate html code in .html.erb file
controller:-
#test = ("<h1>Test case</h1>").html_safe
html.erb:-
<%= #test %>
Try below code to print html on page:
Controller
#data = "<h1>Testing...</h1>"
#data=+ "<h2>Hello</h2>"
view
<%= #data.html_safe %>
OR
<%= raw(#data) %>
Controller
#data = "<h1>Testing...</h1>"
#data=+ "<h2>Hello</h2>"
Views
<%= #data.html_safe%>
Related
I have a form that needs to submit a .csv file to the server and then append the words in it to a textarea in my page. I am using Remotipart to upload the .csv using AJAX but I cannot get the javascript in the server response to execute. Here are the relevant parts of my code:
The Form:
=form_tag(upload_canvas_words_admin_page_widget_widget_instance_path(widget.page, widget),:method=>'post',:remote=>true,:multipart=>true,:class=>"upload_words_csv") do
= label_tag "Upload File"
= file_field_tag "file"
= submit_tag "Upload"
The Controller:
def upload_canvas_words
#csv_text = params[:file].read
end
The .js.haml file:
= remotipart_response do
- if remotipart_submitted?
alert('#{#csv_text}');
alert('!');
- else
alert('WHYYYYY?');
When I look at the response I see the javascript being wrapped in a bunch of html, which I assume has something to do with the iFrame transport. But the javascript never actually executes.
Refer this issue. And try to follow the solution given here.
https://github.com/JangoSteve/remotipart/issues/89
So what happens is that reponse arrives to the browser with html entity (like ") inside the textarea. When the js code for evaluation is extracted the html entities are replaced by theirs respective characters (like " to ').
That's a characteristic of a textarea. So it doesn't get executed
Adding data: {type: :script} to the form should be the fix
say I have an action template like this
# home/index.html.erb
<%= img_tag "logo.gif" %>
if I want to add alt/title attribute to it, I can just do
# home/index.html.erb
<%= img_tag "logo.gif", alt: "alt!!", title: "title!!" %>
but I have 1000 image tags and I don't want to change every each one of them.
I then thought of using rack middleware and modify image tags before outputting from server.
http://railscasts.com/episodes/151-rack-middleware?view=asciicast
doc = Nokogiri.HTML(#response.body)
doc.search("img").each do |tag|
[:alt, :title].each{|attribute| tag[attribute] = "changed!!" }
end
but when I follow the railscast episode, it appends entire body on the top of the original rather than replacing it.
Am I doing it wrong in the rack, or is there a smarter way to do this?
Updated answer:
# /config/initializers/image_tag_helper.rb
module ActionView
module Helpers
module AssetTagHelper
def image_tag(source, options={})
options[:src] = path_to_image(source)
options[:alt] = "Default Alt" unless options.has_key?(:alt)
options[:title] = "Default Title" unless options.has_key?(:title)
tag(:img, options)
end
end
end
end
This overrides the image_tag helper method to set default alt and title attributes.
Is it possible to get the name of the currently rendered view from inside layout?
I did something like this for css namespacing:
# config/initializers/action_view.rb
ActionView::TemplateRenderer.class_eval do
def render_template_with_tracking(template, layout_name = nil, locals = {})
# with this gsub, we convert a file path /folder1/folder2/subfolder/filename.html.erb to subfolder-filename
#view.instance_variable_set(:#_rendered_template, template.inspect.gsub(/(\..*)/, '').split('/')[-2..-1].join('-'))
out = render_template_without_tracking(template, layout_name, locals)
#view.instance_variable_set(:#_rendered_template, nil)
return out
end
alias_method_chain :render_template, :tracking
end
# application.html.erb
<body class="<%= :#_rendered_template %>" >
Use <% __FILE__ %> to get the complete file path of current view, but you can only use it from within the file itself without writing some helpers
The method active_template_virtual_path method returns the template as a name in the following form "controller/action"
class ActionController::Base
attr_accessor :active_template
def active_template_virtual_path
self.active_template.virtual_path if self.active_template
end
end
class ActionView::TemplateRenderer
alias_method :_render_template_original, :render_template
def render_template(template, layout_name = nil, locals = {})
#view.controller.active_template = template if #view.controller
result = _render_template_original( template, layout_name, locals)
#view.controller.active_template = nil if #view.controller
return result
end
end
I had a similar question. I found <%= params[:controller] %> and <%= params[:action] %> to suit my need, which was to add the controller name and action name as classes on the body tag.
Just in case that helps anyone. :)
I'm currently using a modified version of Peter Ehrlich's solution. The resulting string is of the form controller_name/view_name, e.g. users/new, which means it can be passed directly to render later on, or altered to suit other uses. I've only tried this with Rails 4.2, though as far as I know it ought to work all the way back into the 3.xes.
ActionView::Base.class_eval do
attr_accessor :current_template
end
ActionView::TemplateRenderer.class_eval do
def render_template_with_current_template_accessor(template, layout_name = nil, locals = {})
#view.current_template = template.try(:virtual_path)
render_template_without_current_template_accessor(template, layout_name, locals)
end
alias_method_chain :render_template, :current_template_accessor
end
For debugging purpose, you can use gem 'current_template' from here.
This gem inspects logfile and display file name of view/partial template.
For example:
Also, you can simply add this line
<%= "#{`tail log/development.log`}".scan(/\s[a-z]+\/\S+/) %>
to your layout/application.html.erb.
Here is the parent question: save string to file
I want to pass the parameter which will be saved in file(.csv) after clicking button.
#bigtable is a table with strings in each row.
Here is the code in my show.html.erb:
...some code here...
<%= form_tag do %>
<% text_field_tag, id = "bigtable", value = #bigtable.to_s %>
<%= submit_tag 'Zapisz' %>
<% end %>
and my controller method:
def savefile
#bigtable = param[:bigtable]
#bigtable.join("\n")
File.open("path/to/file", "w") { |file| file.write #bigtable.join("\n") }
end
But mine code doesn't work :/
I want to save #bigtable strings to file. Each row record of the table is a new line of the file. And I want to save file without redirecting current page anywhere but completely don't know why:( Please help.
okay, I know why it doesn't work - I shoud add some new route to initialize savefile method - but how do it without redirecting/refreshing current page with results? plz help
Use <%= form_tag(url, :remote => true) do %> to make the call with Ajax, so your page will not be redirected. Use your server logs to see if the request is executed (if you want to get the result of the ajax call in your page, look at http://www.alfajango.com/blog/rails-3-remote-links-and-forms/).
I've found a solution - to not write double post here is the link to the topic with the answer: saving variable to file and downloading it
If i have the following javascript code
var myVar = 0;
function setNewValforVar(newValue){
myVar = newValue;
}
and i'm calling setNewValforVar function n times
so when I click on a link it'd send myVar value to the controller action in a remote link like
<%=link_to "My Link",{:action=>"myAction"},:data=>''sval='+myVar',:remote=>true%>
I Rails 2.3.x I'd do this with
<%=link_to_remote "My Link",:url=>{:action=>"myAction"},:with=>"'sval='+myVar"%>
and i was getting this on the controller's action with
params["myVar"]
how do I do this on Rails 3 with the link_to helper?
Rails 3 no longer supports this behavior. You will have to either create a form to submit the value, or modify the href of the link to include the value in the query string.
I found some solution that use callbacks. Link must be marked in some way, for example by adding the id:
<%=link_to "My Link", {:action=>"myAction"}, :remote=>true, :id => "mylink" %>
There is an example for prototype_ujs: the parameter is simply appended to the request's URL (the code is a bit simplified I assume that some parameters already exist).
<%= javascript_tag("document.on('ajax:create', 'a#mylink',
function(event) { event.memo.request.url += '&sval=' + myVar; })") %>
Some advantage of this (ugly a bit) solution is the possibility of using one function for a particular class of links instead of the indicated id.