0

Let's say I have a span division such as

<span class="foodtype" id="food<%=category%>">

and I want to, in the HTML, remove white space from the category (e.g Fruit or Vegetable --> FruitOrVegetable) so that the ID doesn't contain spaces. How can I do this?

Also, could someone explain what the <%= %> refers to?

4 Answers4

0

It's probably best to write like this -

<span class="food" data-category="fruit" id="apple"></span>

this improves readability. This approach would mean that you can avoid having to deal with spaces etc. Just focus on defining the span using data tags.

Also your question about the <%= %>, they are expression tags pointed out by @orde, they will be stripped out when the code is compiled and the value of the "category" variable will be injected into the id tag.

Hope this helps! :) good luck!

Konda
  • 78
  • 1
  • 8
0

<%= %> tells the erb file to render/print the result, not just execute it.

<% %> just executes the ruby in line and does not print the result. Examples might be setting a variable or creating a loop.

Here are some docs: http://apidock.com/ruby/ERB

There are many methods you can use to manipulate a string in ruby, gsub or delete would work well for this since the whitespace will be throughout the string:

https://ruby-doc.org/core-2.3.1/String.html#method-i-delete

It is best to finish manipulating your data prior to passing it to the view. You may want to consider removing the spaces in a view helper if you are using Rails.

Teresa
  • 75
  • 7
0
category = 'Fruit or Vegetable'

category.gsub(' ','') #=> 'FruitsorVegetables'

category.titleize.gsub(' ','') #=> 'FruitsOrVegetables'

So this may do the trick

<span class="foodtype" id="food<%=category.gsub(' ','')%>">

or

<span class="foodtype" id="food<%=category.titleize.gsub(' ','')%>">
Sajin
  • 1,608
  • 1
  • 14
  • 18
  • Don't forget code formatting on the code there. The `{}` button usually fixes selected chunks in a single click. – tadman Mar 15 '17 at 04:20
0

<%= %> in html.erb file is used to print ruby code in html file.

<span class="foodtype" id="food<%=category.gsub(' ','')%>">
puneet18
  • 4,341
  • 2
  • 21
  • 27