Class: Decidim::ContentRenderers::LinkRenderer

Inherits:
BaseRenderer
  • Object
show all
Defined in:
lib/decidim/content_renderers/link_renderer.rb

Overview

Original: github.com/neighborland/anchored/ A renderer that converts URLs to links and strips attributes in anchors.

Examples: ‘<a href=“urls.net” onmouseover=“alert(’hello’)”>URLs</a>‘ Gets rendered as: `<a href=“decidim.org” target=“_blank” rel=“noopener”>decidim.org</a>` And: `<a href=“javascript:document.cookies”>click me</a>` Gets rendered as: `click me`

Instance Attribute Summary

Attributes inherited from BaseRenderer

#content

Instance Method Summary collapse

Methods inherited from BaseRenderer

#initialize

Methods included from Decidim::ContentProcessor::Common

#html_content?, #html_fragment

Constructor Details

This class inherits a constructor from Decidim::ContentRenderers::BaseRenderer

Instance Method Details



37
38
39
40
41
# File 'lib/decidim/content_renderers/link_renderer.rb', line 37

def auto_link(text, options = {}, &)
  return "" if text.to_s.empty?

  auto_link_urls(text, options, &)
end

#remove_target_if_local(href, domain, options) ⇒ Object

remove_target_if_local(“same.com/x”, “same.com”, target: “_blank”)

> <a href=“same.com/x”>same.com/x</a>

remove_target_if_local(“same.com/x”, “different.com”, target: “_blank”)

> <a href=“same.com/x” target=“_blank”>same.com/x</a>

modifies options in place



50
51
52
53
54
# File 'lib/decidim/content_renderers/link_renderer.rb', line 50

def remove_target_if_local(href, domain, options)
  return unless options[:target]

  options.delete(:target) if href.include?("//#{domain}")
end

#render(options = {}) ⇒ String

Returns the content ready to display (contains HTML).

Returns:

  • (String)

    the content ready to display (contains HTML)



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/decidim/content_renderers/link_renderer.rb', line 20

def render(options = {})
  return content unless content.is_a?(String)

  options = { target: "_blank", rel: "nofollow noopener noreferrer ugc" }.merge(options.transform_keys(&:to_sym))
  rendered = auto_link(content, options)

  # In case the content was already in HTML format, it may be that it
  # contained links that were incorrectly formatted, e.g. with incorrect
  # attributes.
  fragment = html_fragment(rendered)
  fragment.search("a[href]").each do |el|
    attrs = el.attributes.transform_keys(&:to_sym).transform_values(&:value)
    el.replace anchor_tag(attrs.delete(:href), el.inner_html, attrs.merge(options))
  end
  fragment.to_s
end