Glyph – Custom Output Formats

As shown in How Commands and Tasks work, the compile command command calls specific tasks defined in the generate: Rake namespace to generate output files in a particular format.

More specifically, when a --format option is specified, the command looks for a task with the same name within the generate: namespace. This makes adding new output formats to Glyph a fairly easy task, without the need to specify custom commands or similar.

The following sections explain how the h3rald output format was created to integrate this book into the H3RALD.com website.

Output Configuration

The first step required to add a new output format to Glyph is extending Glyph’s configuration by adding the appropriate output hash, as follows:

 1:output: 
 2  :h3rald: 
 3    :multifile: true
 4    :extension: '.html'
 5    :filter_target: 'html'
 6    :base: '/glyph/book/'
 7    :macro_dirs: ['html', 'html5']
 8    :layout_dirs: ['web5']
 9    :layouts: 
10      :topic: bookpage
11      :index: bookindex

In particular, the following keys are mandatory:

  • multifile
  • extension
  • filter_target
  • base
  • macro_dirs
  • layout_dirs

Creating a 'generate:h3rald' task

The next (and final) step involves creating a custom h3rald task within the generate: namespace. This task can be placed in any .rake file within the lib/tasks directory:

 1namespace :generate do
 2  desc "Create output for h3rald.com integration"
 3  task :h3rald => [:web5] do
 4    dir = Glyph::PROJECT/'output/h3rald'
 5    (dir/"glyph/book").mkpath
 6    # Copy files in subdir
 7    (dir).find do |i|
 8      if i.file? then
 9        next if i.to_s.match(Regexp.escape(dir/'glyph')) 
10        dest = dir/"glyph/book/#{i.relative_path_from(Glyph::PROJECT/dir)}"
11        src = i.to_s
12        Pathname.new(dest).parent.mkpath
13        file_copy src, dest
14      end
15    end
16    # Remove files from output dir
17    dir.children.each do |c|
18      unless c == dir/'glyph' then
19        c.directory? ? c.rmtree : c.unlink
20      end
21    end
22    (dir/'glyph/book/images/glyph/glyph.eps').unlink 
23    (dir/'glyph/book/images/glyph/glyph.svg').unlink
24    # Create project page
25    project = Glyph.filter %{layout:project[
26        @contents[#{file_load(Glyph::PROJECT/'text/introduction.glyph')}]
27      ]}
28    file_write dir/"glyph.textile", project
29  end  
30end

In this case, this task does not actually renders files in a different format, it just moves the files generated by the @generate:web5@ task in different subdirectories.

Additionally, it also generates the Glyph project page from the book's introduction (note the usage of a raw custom layout macro).