Class: BlockEditor::BlockListRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/block_editor/block_list_renderer.rb

Overview

Handles the rendering of a block list including dynamic blocks and removing HTML comments

Class Method Summary collapse

Class Method Details

.render(raw_html) ⇒ String

Renders dynamic blocks within the HTML snippet then strips all HTML comments (including Gutenberg markup)

Parameters:

  • raw_html (String)

Returns:

  • (String)

    Parsed content



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/block_editor/block_list_renderer.rb', line 9

def self.render(raw_html)
  html = Nokogiri::HTML::DocumentFragment.parse(raw_html)

  # Find & render all instances of a dynamic block (including reusable blocks)
  BlockEditor.dynamic_blocks.each do |dynamic_block|
    dynamic_block = dynamic_block.constantize

    html.search('.//comment()').select {|comment| comment.inner_text.starts_with?(" wp:#{dynamic_block.name}") }.each do |block_instance|
      block_attributes = block_instance.inner_text.split(" wp:#{dynamic_block.name}")[1][0...-1]
      block_attributes = block_attributes.blank? ? {} : JSON.parse(block_attributes)
      block_content = render_block(dynamic_block, block_attributes)

      block_instance.replace(block_content)
    end
  end

  html.search('.//comment()').remove
  html.to_s.html_safe
end

.render_block(block, options) ⇒ String

Renders a specific block using the provided options

Parameters:

  • block (String)

    name of block

  • options (Hash)

    block options to use when rendering

Returns:

  • (String)

    block content (HTML)



35
36
37
38
39
# File 'lib/block_editor/block_list_renderer.rb', line 35

def self.render_block(block, options)
  block.render(options)
rescue StandardError => e
  respond_with_block_error(e)
end

.respond_with_block_error(error) ⇒ Object

Handles block errors



42
43
44
45
# File 'lib/block_editor/block_list_renderer.rb', line 42

def self.respond_with_block_error(error)
  Rails.logger.error("Error rendering block - #{error.message}")
  ''
end