Add target=blank to links in formatted text via js
This commit is contained in:
parent
d90f1b86b8
commit
812c192910
5 changed files with 18 additions and 28 deletions
|
|
@ -16,9 +16,11 @@ application.register("collapse-chevron-toggler", CollapseChevronTogglerControlle
|
|||
import HelloController from "./hello_controller"
|
||||
application.register("hello", HelloController)
|
||||
|
||||
import RichTextLinkTargetsController from "./rich_text_link_targets_controller"
|
||||
application.register("rich-text-link-targets", RichTextLinkTargetsController)
|
||||
|
||||
import SetThemeController from "./set_theme_controller"
|
||||
application.register("set-theme", SetThemeController)
|
||||
|
||||
import ThemeSwitcherController from "./theme_switcher_controller"
|
||||
application.register("theme-switcher", ThemeSwitcherController)
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
// Connects to data-controller="rich-text-link-targets"
|
||||
export default class extends Controller {
|
||||
connect() {
|
||||
this.element.querySelectorAll('div.trix-content a').forEach(function(link) {
|
||||
if (link.host !== window.location.host) {
|
||||
link.target = "_blank"
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,6 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class Check < ApplicationRecord
|
||||
include RichTextTargetBlank
|
||||
|
||||
belongs_to :principle
|
||||
|
||||
has_and_belongs_to_many :links
|
||||
|
|
|
|||
|
|
@ -1,24 +0,0 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
module RichTextTargetBlank
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
class_methods do
|
||||
# Override has_rich_text to include target="_blank" functionality
|
||||
def has_rich_text(name)
|
||||
super # Call the original has_rich_text to set up the rich text association
|
||||
|
||||
# Define the before_save callback to modify the links
|
||||
before_save do
|
||||
next # FIXME: This adds additional newlines for each blank line.
|
||||
|
||||
rich_text_attribute = send(name)
|
||||
if rich_text_attribute.present?
|
||||
doc = Nokogiri::HTML::DocumentFragment.parse(rich_text_attribute.body.to_html)
|
||||
doc.css("a").each { |a| a["target"] ||= "_blank" }
|
||||
rich_text_attribute.body = doc.to_html
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
@ -23,8 +23,10 @@
|
|||
<a href="#" data-bs-target="#sidebar" data-bs-toggle="collapse" class="p-1 text-decoration-none"><i class="bi bi-list bi-lg py-2 p-1"></i> Menu</a>
|
||||
<% end %>
|
||||
|
||||
<div id="main-content" data-controller="rich-text-link-targets">
|
||||
<%= yield %>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue