Home > Enterprise >  HTML removes wanted spaces in between text
HTML removes wanted spaces in between text

Time:12-24

I have a question quite opposite to the questions already asked here. Let me just start off with the example.

When I go to rails console and type Stock.where(item_code: "1234").pluck(:description)

I get the following:

(4.5ms) SELECT "stocks"."description" FROM "stocks" WHERE "stocks"."item_code" = ? [["item_code", "1234"]] => ["R Bag1234", "R Bag1234"]

As you can see there are clearly 2 spaces in the description

R Bag1234

But when I print this in my view using a loop, one space is removed. i.e. the description is

R Bag1234

And I do not want any spaces to be removed. Please advice what to do lol. Thanks!

Here's a snippet of the view (index.html.erb)

<% @stocks.each do |stock| %>
        <tr>
          <td><%= stock.item_code %></td>
          <td><%= stock.description %></td>
          <td><%= stock.item_unit %></td>
          <td><%= stock.stock %></td>
        <tr>
<% end %>        

Here's a snippet of the controller (stocks_controller.rb)

class StocksController < ApplicationController
  before_action :set_stock, only: %i[ show edit update destroy ]

  # GET /stocks or /stocks.json
  def index
    @stocks = Stock.all
  end

And my schema.rb looks like this

ActiveRecord::Schema.define(version: 2021_12_23_215326) do

  create_table "stocks", force: :cascade do |t|
    t.string "item_code"
    t.text "description"
    t.string "item_unit"
    t.decimal "stock"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end

Ah also, I am using ruby 3.0.0 and rails 6.1.4 on windows 10

EDIT:

After a helpful comment, seems like it is an issue with HTML and nothing much to do with RoR. For Example: https://jsfiddle.net/ugvkqsn2/ the code in the above example shows 2 spaces with pure html but the browser only shows 1 space.

CodePudding user response:

Set the white-space CSS property to pre on the <td> elements where you don't want the whitespace to collapse like this:

<% @stocks.each do |stock| %>
    <tr>
      <td><%= stock.item_code %></td>
      <td style="white-space: pre;"><%= stock.description %></td>
      <td><%= stock.item_unit %></td>
      <td><%= stock.stock %></td>
    <tr>
<% end %>  
  • Related