I need to create an HTML fragment to embed in a page (a simple js gallery). This is the HTML:
<div id="gallery-1" class="royalSlider rsDefault">
<a class="rsImg" data-rsw="632" data-rsh="500" data-rsbigimg="../img/paintings/2.jpg" href="../img/paintings/700x500/2.jpg">
Vincent van Gogh - The Starry Night
<img width="96" height="72" class="rsTmb" src="../img/paintings/t/2.jpg">
</a>
</div>
I can create this using string interpolation, but someone suggest me to use Nokogiri. I do not know how I can nest the nodes.
#doc = Nokogiri::HTML::DocumentFragment.parse ""
Nokogiri::HTML::Builder.with(#doc) do |doc|
g.pictures.each do |picture|
doc.create_element "a", :class => "rsImg"
end
end
Is it better to use Nokogiri, or can I also proceed with the easy way (string)? How can I create the nested structure I need?
Update
Done with Nokogiri
#doc = Nokogiri::HTML::DocumentFragment.parse ""
Nokogiri::HTML::Builder.with(#doc) do |doc|
doc.div(:id => 'content-gallery', :class => 'royalSlider rsDefault') {
g.pictures.each do |picture|
doc.a(:src => picture.image_url(:gallery), :class => 'rsImg') {
doc.img(:src => picture.image_url(:widget), :class => 'rsTmb')
}
end
}
end
#doc.to_html
Related
I am trying to wrap div-equalizer-watch inside content_tag but the div-equalizer-watch is getting print (
{:"data-equalizer-watch"=>"", :class=>"list_users"}). Can someone guide me where I am doing wrong
Below, is the HTML which I am trying to write in rails helper with content_tag & capture tag
<a href="/ussers/profile" target="_blank">
<div class="list_users" data-equalizer-watch="">
<h2>Cost</h2>
</div>
</a>
content_tag :a, href: "/ussers/profile", target: '_blank' do
capture do
concat (content_tag :div, :"data-equalizer-watch" => "",:class => 'list_users')
concat (content_tag :h2, 'Cost')
end
end
Finally got the solution
content_tag :a, href: '/ussers/profile', target: '_blank' do
capture do
concat (content_tag :div, nil, :"data-equalizer-watch" => "", :class => 'list_users' do
concat (content_tag :h2, title)
end )
end
end
Took reference from this link
Right now I have my ActionView::Base.field_error_proc as
Proc.new do |html_tag, instance|
if html_tag =~ /^<label/ or instance.respond_to?(:object_name)
%{<div class="field_with_errors">#{html_tag}</div>}.html_safe
else
%{<div class="field_with_errors">#{html_tag}<br /><label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
end
I had modified this to accomodate a few of my needs when i did use the client_side_validations gems.
Right now, the 'fields_with_error' div wraps around the html_tag(i.e the error field to be specific). What i would like to know though is if its possible to modify the position of the div class="fields_with_error" and place it right after the div that contains the error_field.
For eg,
<div class="main_div">
<%= password_field_tag 'secret', 'Your secret here' %>
</div>
Then the div class="fields_with_error" should be postioned as
<div class="main_div">
<%= password_field_tag 'secret', 'Your secret here' %>
</div>
<div class="fields_with_error"> <label class="message"> The error message </label> </div>
Any help would be of great value.
So when I work with twitter bootstrap I usually make an initializer with something like this
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
html = %(<div class="field_with_errors">#{html_tag}</div>).html_safe
# add nokogiri gem to Gemfile
form_fields = [
'textarea',
'input',
'select'
]
elements = Nokogiri::HTML::DocumentFragment.parse(html_tag).css "label, " + form_fields.join(', ')
elements.each do |e|
if e.node_name.eql? 'label'
html = %(<div class="control-group error">#{e}</div>).html_safe
elsif form_fields.include? e.node_name
if instance.error_message.kind_of?(Array)
html = %(<div class="control-group error">#{html_tag}<span class="help-inline"> #{instance.error_message.uniq.join(', ')}</span></div>).html_safe
else
html = %(<div class="control-group error">#{html_tag}<span class="help-inline"> #{instance.error_message}</span></div>).html_safe
end
end
end
html
end
This just adjust regular errors to twitter errors in forms :> so makes everything very nice to look at ;>. You can use same approach.
Cheers if this helps
I am using erb and ideally, I would like my html to look like this:
<li class="selected">Look at this awesome page</li>
Where both the path for the link, and the class for the li are dynamically generated using an instance variable.
Thoughts?
Edit 1
If I were using something like Rails, I know I could probably do something like:
<%= link_to content_tag(:li, nil, awesome_path, :class => "selected") %>
But that would produce the opposite effect, where the <a> would be outside of the <li> and not inside where I want it.
That's called a helper:
helpers do
def li_with_a options
'<li class="' + options[:class] + '">' + options[:text] + '</li>'
end
end
and from erb:
<%= li_with_a :class => 'selected', :url => 'awesome.html', :text => 'Look at this text' %>
Should be as easy as:
<li class="<%= #li_class %>">
Look at this awesome page
</li>
Of course you have to change the instance variables accordingly.
I feel like there is a large step from where Rails tutorials end and where I can actually use it to do what I need. This is manifesting itself in this relatively simple case:
I want a page that takes inputs and calculates a volume. Ideally, this would do it with AJAX because it always irritates me when a simple page makes me reload it.
I've been doing this in IRB with:
radius = 25; length = 0.15;( radius**2) * Math::PI * length *1e-3
# radius in microns, length in meters, answer in microliters
But the confusion comes in just about here. I understand that I must route a page, I understand that my controller is responsible for directing to the correct response, but where should my calculation occur? How do I capture the responses for my form?
I just don't seem to understand how to integrate all these things...
Here's my view (which renders, but from which I can't seem to feed the information in or out:
<h2>Here I'll calculate the dead volume of a piece of tubing for you.</h2>
<%= form_tag url_for(:method => :get), :remote => true, :id => 'calculation_entry' do %>
<div id="internal_diameter">
<label for="diameter">Enter the internal diameter:</label>
<%= text_field_tag :diameter %>
<label for="diameter_unit"></label>
<%= select_tag :diameter_unit, options_for_select({
"Microns" => 'micrometers',
'inches' => 'inches'
}) %>
</div>
<div id="length">
<label for="length">Enter the length of tubing:</label>
<%= text_field_tag :length %>
<label for="length_unit"></label>
<%= select_tag :length_unit, options_for_select({
"meters" => 'meters',
"inches" => 'inches'
}) %>
</div>
<%= submit_tag "Calculate!" %>
<% end %>
<div class="output">
<span>The volume of the tubing parameters entered is:</span>
<%= #object %>
</div>
And here is the controller I've built:
class PagesController < ApplicationController
def index
end
def dead_volume
#object = Object.new
end
def calculate
#object = params.inspect
end
end
Here is an example of how I implemented autocomplete functionality with jQuery UI & Ajax. It may help you to determine how to do this for your own application's needs.
Note: This is was done under Rails 3.0.X. There are probably other/better ways to do this.
View/Layout:
<div id="search">
<%= form_tag('/<my_controller>/search', :method => :get, :id => "#search-text") do %>
<input type="text" name="search" value="" id="search-text" placeholder="Search">
<input type="submit" value="Go" class="button">
<% end %>
</div>
JavaScript (note: uses jQuery UI):
$(document).ready(function() {
$("#search-text").autocomplete({
source: function(request, response) {
$.getJSON("/<my_controller>/autocomplete", {
search: request.term
},
response);
},
minLength: 2,
select: function(event, ui) {
this.value = ui.item.value;
return false;
},
});
});
Route:
match '/<my_controller>/autocomplete' => '<my_controller>#autocomplete', :via => :get
Controller:
respond_to :json, :only => [:autocomplete]
def autocomplete
#model = Model.autocomplete(params[:search])
render(:json => #model)
end
I hope this helps you get on your way.
Given:
require 'rubygems'
require 'nokogiri'
value = Nokogiri::HTML.parse(<<-HTML_END)
"<html>
<body>
<p id='para-1'>A</p>
<div class='block' id='X1'>
<h1>Foo</h1>
<p id='para-2'>B</p>
</div>
<p id='para-3'>C</p>
<h2>Bar</h2>
<p id='para-4'>D</p>
<p id='para-5'>E</p>
<div class='block' id='X2'>
<p id='para-6'>F</p>
</div>
</body>
</html>"
HTML_END
I want to do something like what I can do in Hpricot:
divs = value.search('//div[#id^="para-"]')
How do I do a pattern search for elements in XPath style?
Where would I find the documentation to help me? I didn't see this in the rdocs.
Use the xpath function starts-with:
value.xpath('//p[starts-with(#id, "para-")]').each { |x| puts x['id'] }
divs = value.css('div[id^="para-"]')
And some docs you're seeking:
Nokogiri: http://nokogiri.org/
XPath: http://www.w3.org/TR/xpath20/
CSS3 Selectors: http://www.w3.org/TR/selectors/
Nokogiri::XML::Node.send(:define_method, 'xpath_regex') { |*args|
xpath = args[0]
rgxp = /\/([a-z]+)\[#([a-z\-]+)~=\/(.*?)\/\]/
xpath.gsub!(rgxp) { |s| m = s.match(rgxp); "/#{m[1]}[regex(.,'#{m[2]}','#{m[3]}')]" }
self.xpath(xpath, Class.new {
def regex node_set, attr, regex
node_set.find_all { |node| node[attr] =~ /#{regex}/ }
end
}.new)
}
Usage:
divs = Nokogiri::HTML(page.root.to_html).
xpath_regex("//div[#class~=/axtarget$/]//div[#class~=/^carbo/]")