1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Apply Basic HTML Formatting To Block Of Text as a Rails TIL

This commit is contained in:
jbranchaud
2025-01-21 15:48:40 -06:00
parent c2184a5ecf
commit 8b3ef4872c
2 changed files with 42 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1570 TILs and counting..._
_1571 TILs and counting..._
See some of the other learning resources I work on:
- [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators)
@@ -954,6 +954,7 @@ See some of the other learning resources I work on:
- [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md)
- [Alphabetize Schema Columns To Keep Them Consistent](rails/alphabetize-schema-columns-to-keep-them-consistent.md)
- [Alter The Rails Setup Script](rails/alter-the-rails-setup-script.md)
- [Apply Basic HTML Formatting To Block Of Text](rails/apply-basic-html-formatting-to-block-of-text.md)
- [Assert Two Arrays Have The Same Items With RSpec](rails/assert-two-arrays-have-the-same-items-with-rspec.md)
- [Attach A File With Capybara](rails/attach-a-file-with-capybara.md)
- [Attribute Getter without the Recursion](rails/attribute-getter-without-the-recursion.md)

View File

@@ -0,0 +1,40 @@
# Apply Basic HTML Formatting To Block Of Text
My Rails app has a form that allows a user to enter in free-form text. I enter
in a couple paragraphs and save the record. It is rendered on a show page with
a couple lines of ERB like so:
```ruby
<div class="max-w-3xl mx-auto">
<div class="space-y-4">
<div class="prose mt-8 text-gray-700">
<%= @record.notes %>
</div>
</div>
</div>
```
When I view the erb-displayed version of that record's text, all those
carefully spaced paragraphs are clumped together. That is because those newline
(`\n` and `\n\n`) characters while understood to be whitespace do not have
formatting implications in the browser like a combination of HTML tags and CSS
do.
I can apply some basic formatting with [the aptly named `simple_format` method
available as an `ActionView`
helper](https://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format).
```ruby
<div class="max-w-3xl mx-auto">
<div class="space-y-4">
<div class="prose mt-8 text-gray-700">
<%= simple_format(@record.notes) %>
</div>
</div>
</div>
```
This turns single `\n` characters into a `<br />` tag and double `\n\n` cause
the surrounding paragraphs to be wrapped in `<p>` tags. That simple formatting
combined with my existing TailwindCSS styles makes the formatting of my text
immediately look much better.