500004dolkong
500004dolkong

Reputation: 765

How can I insert variable in the HTML body?

I implemented the scripts that appending a child in the existing HTML body. When I append a new child, I want to use variable in the value.

For example:

date=Time.now.strftime("%Y-%m-%d") 

orig_html = defect.Field(@td_columns[:"Comments"])
  #XML module only provides html parsing without the DOCTYPE tag.
doc = Nokogiri::XML::DocumentFragment.parse(orig_html)    
tmp1 = '<div align="left"><font face="Arial"><span style="font-size:9pt">#{date}</span></font></div>'
child1 = Nokogiri::XML::fragment(tmp1)
body = doc.at('body')
body.add_child(child1)

But, the date variable is not displayed as an actual date (ex. 2015-02-09) but just #{date}.

Does anyone have advice to insert variables in HTML contents?

Upvotes: 0

Views: 874

Answers (2)

the Tin Man
the Tin Man

Reputation: 160631

You're using a single-quote delimited string which doesn't allow interpolation of variables. Instead you have to use a double-quote delimited string or one of the forms that allows interpolation:

var_a = 'var_b'
'#{ var_a }'   # => "\#{ var_a }"
%q[#{ var_a }] # => "\#{ var_a }"
"#{ var_a }"   # => "var_b"
%[#{ var_a }]  # => "var_b"
%Q[#{ var_a }] # => "var_b"

Your code is too complicated. You can simplify it using:

tmp1 = "<div align='left'><font face='Arial'><span style='font-size:9pt'>#{date}</span></font></div>"
body = doc.at('body')
body.add_child(tmp1)

Nokogiri is smart enough to know it should convert the contents of tmp1 into the equivalent HTML so you don't have to do it for it:

require 'nokogiri'

date = Time.now

doc = Nokogiri::HTML('<html><body></body></html>')
tmp1 = "<div align='left'><font face='Arial'><span style='font-size:9pt'>#{date}</span></font></div>"
body = doc.at('body')
body.add_child(tmp1)
puts body.to_html
# >> <body><div align="left"><font face="Arial"><span style="font-size:9pt">2015-02-08 23:30:49 -0700</span></font></div></body>

Upvotes: 1

spickermann
spickermann

Reputation: 107142

String interpolation only works with double quotes:

foo = 'bar'
"foo #{foo} foo" # works and returns 'foo bar foo' 
'foo #{foo} foo' # does not work: 'foo #{foo} foo'

That said, change the quotes to double quotes (and escape existing double quotes) in the following line:

tmp1 = "<div align=\"left\"><font face=\"Arial\"><span style=\"font-size:9pt\">#{date}</span></font></div>"

Upvotes: 2

Related Questions