class HTMLPage

Constants

Attributes

user-defined attributes

ERB_EVAL_OPERATORS
PageAttributes

page attributes are available to templates

TEMPLATES_DIR

Attributes

page[R]

Public Class Methods

new(content_filename, layout_filename = nil) click to toggle source

Compile an HTML page from the content_filename and layout_filename sources.

Content files must be markdown or embedded ruby and have an “md” or “erb” extension. If markdown, content is first evaluated as Erb. Layouts files must be “erb”. The content renders within the layout template if specified.

Attributes specified in the preamble of the content file will be set in page and are available to layout and embedded templates.

# File lib/html_page.rb, line 25
def initialize(content_filename, layout_filename = nil)
  @content_filename = content_filename
  @layout_filename  = layout_filename&.delete_prefix(TEMPLATES_DIR)
  @page = PageAttributes.new
end

Public Instance Methods

render() click to toggle source

Returns the rendered HTML page.

# File lib/html_page.rb, line 34
def render
  f = File.new(@content_filename)

  # parse attributes and content
  while (line = f.gets)
    case line
    when /^(\w+):(.*)/  # begin attribute
      begin
        attribute = page[$1.downcase] = $2.strip
      rescue NameError => e
        raise e.class, "Bad page attribute `#{$1}'.\n"\
          "Valid attributes: #{Attributes.to_s.tr('[:]','')}"
      end
    when /^\s*$/        # end attribute (blank lines between attrs)
      attribute = nil
    else
      unless attribute  # remainder is content
        content = line
        content << f.gets(nil) unless f.eof?
        break
      end
      attribute << (attribute.empty? ? '':' ') << line.strip
    end
  end

  f.close
  content = instance_eval(transform(content)).call # process with erb

  if @content_filename.end_with? '.md'
    if page.title.nil? # then use H1
      page.title = content[/^#\s+([^#\{\r\n]+)/, 1]&.rstrip
    end
    opts = { auto_ids: false }
    content = Kramdown::Document.new(content, opts).to_html
  end

  if @layout_filename
    page.content = content
    template(@layout_filename) # page.content embedded in layout
  else
    content # without a layout
  end
end