Class: StaticSiteBuilder::HTMLTemplater

Inherits:
Object
  • Object
show all
Defined in:
lib/static_site_builder/html_templater.rb

Constant Summary collapse

EDITABLE_REGION =
'<div id="editable_region"></div>'.freeze
DEFAULT_TEMPLATE =
"templates/default_template.html".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template_filepath: DEFAULT_TEMPLATE, gem_included_template: true, html: nil) ⇒ HTMLTemplater

Initializes a HTML template with either a template_filepath to a HTML file or a HTML string. Either way the HTML should be valid and contain the EDITABLE_REGION. If no params are provided then the DEFAULT_TEMPLATE is used instead. The DEFAULT_TEMPLATE uses bootstrap 4 (from a CDN). The html takes precedence over the template_filepath if provided. The gem_included_template param distinguishes between a user created template (on their local file system) and an included template (built into the gem) e.g. the DEFAULT_TEMPLATE.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/static_site_builder/html_templater.rb', line 16

def initialize(
    template_filepath: DEFAULT_TEMPLATE,
    gem_included_template: true,
    html: nil
  )
  @template_filepath = template_filepath
  @gem_included_template = gem_included_template
  @html = html

  read_template unless @html

  if not valid?
    raise "Missing editable region in template: #{EDITABLE_REGION}"
  end
end

Instance Attribute Details

#gem_included_templateObject (readonly)

Returns the value of attribute gem_included_template.



6
7
8
# File 'lib/static_site_builder/html_templater.rb', line 6

def gem_included_template
  @gem_included_template
end

#htmlObject (readonly)

Returns the value of attribute html.



6
7
8
# File 'lib/static_site_builder/html_templater.rb', line 6

def html
  @html
end

#template_filepathObject (readonly)

Returns the value of attribute template_filepath.



6
7
8
# File 'lib/static_site_builder/html_templater.rb', line 6

def template_filepath
  @template_filepath
end

Instance Method Details

#render(html_body) ⇒ Object

Renders the HTML template by replacing the EDITABLE_REGION with the html_body param. It’s your responsibility to ensure the html_body is valid HTML within the context of a ‘body’ tag e.g. <body>#html_body</body>



42
43
44
# File 'lib/static_site_builder/html_templater.rb', line 42

def render(html_body)
  @html.gsub(EDITABLE_REGION, html_body)
end

#valid?Boolean

Returns wether or not the @html has an EDITABLE_REGION or not. This method does not check if the HTML is valid or not. That’s your responsibility.

Returns:

  • (Boolean)


35
36
37
# File 'lib/static_site_builder/html_templater.rb', line 35

def valid?
  @html.include?(EDITABLE_REGION)
end