html form generation problems

D

Dennis Roberts

I think I must be doing something wrong. I am attempting to generate a
form which values from existing data. Here is a simplified version of
what I am trying to do (see below). I don't get a form element with
this, I get something like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML><BODY><FORM
METHOD="post"
ENCTYPE="application/x-www-form-urlencoded">onetwothree</FORM></BODY></HTML>

I also notice the HEAD and TITLE tags are missing. Any advice?

#!/usr/bin/ruby -w
require 'cgi'
cgi = CGI.new("html3")

ary = %w( one two three )

cgi.out do
cgi.html do
cgi.head do
cgi.title("Form Test")
end
cgi.body do
cgi.form do
ary.each do |value|
cgi.text_field(value, value)
end
end
end
end
end
 
W

why the lucky stiff

Dennis said:
I think I must be doing something wrong. I am attempting to generate
a form which values from existing data. Here is a simplified version
of what I am trying to do (see below). I don't get a form element
with this, I get something like:

I also notice the HEAD and TITLE tags are missing. Any advice?

You'll need to concatenate the various strings together to get this to
work. You might also consider using instance_eval to simplify things.

#!/usr/bin/ruby -w
require 'cgi'
cgi = CGI.new("html3")

ary = %w( one two three )

cgi.instance_eval do
out do
html do
head do
title { "Form Test" }
end +
body do
form do
ary.collect do |value|
text_field value, value
end.join + submit
end
end
end
end
end

_why
 
D

Dennis Roberts

This works! Thanks. What is the difference between each and collect?
With each it still didn't work, but it did with collect.

Thank you for your quick response.
 
W

why the lucky stiff

Dennis said:
This works! Thanks. What is the difference between each and collect?
With each it still didn't work, but it did with collect.

The `each' method merely walks an Array (or other Enumerable.) But
`collect' (a.k.a `map') walks the Array, replacing each element with the
result from the block. At the end of `collect', you have a new Array.

So, in the cgi example, you started with an array of:
['one', 'two', 'three']

The `collect' processes each through the `text_field' method and you
wind up with:
["<INPUT NAME=\"one\" SIZE=\"40\" TYPE=\"text\" VALUE=\"one\">",
"<INPUT NAME=\"two\" SIZE=\"40\" TYPE=\"text\" VALUE=\"two\">", "<INPUT
NAME=\"three\" SIZE=\"40\" TYPE=\"text\" VALUE=\"three\">"]

_why
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top