2

I would like to build logic in to a Jekyll site so that pages of a certain layout will have their YAML validated, with the build erroring if specific fields are missing, or have the wrong type of value, etc.

One workaround is through writing a kludgy plugin for a Liquid filter that simply takes an error message and raises an exception:

module Jekyll
  module ExceptionFilter
    def raise_error(msg)
        bad_file = @context.registers[:page]['path']
        err_msg = "On #{bad_file}: #{msg}"
      raise err_msg
    end
  end
end

Liquid::Template.register_filter(Jekyll::ExceptionFilter)

Then, within a template, for example, I can include this:

{% unless page.necessary_field %}
    {{ "You're missing necessary_field" | raise_error }}
{% endunless %}

This sort of gets the job done.

One problem I have is that the build process halts immediately on finding one error. I would love to be able to continue the build across all the .md files in the repo, and collect a list of the errors across all pages to display at the end. Based on the Jekyll docs, I thought that liquid: error_mode: warn in _config.yml would do this, but it does not.

mdlincoln
  • 274
  • 3
  • 12

1 Answers1

2

You could (ab)use a Generator to check all files before building. Here is how you could do it:

module MyModule

  class WarningGenerator < Jekyll::Generator
    def generate(site)

      errors = Array.new

      site.posts.docs.each do |p|
        unless p.data['my_property'].any? {
           errors = "On #{p.title}: My Property is missing"

        }
      end

      errors.each do |error|
        puts error
      end

      raise "There were errors"
    end
  end
end

Attention, this code is not tested :)

It would walk through all your pages, checks for a specific property, adds a message to an array if it's not found and raises an error afterwards.

Christian
  • 7,062
  • 5
  • 36
  • 39
  • Ah yes, a generator would make more sense as it could iterate over all the pages before finally raising an exception. – mdlincoln May 11 '17 at 15:44
  • The one benefit we're finding to the template / liquid filter solution, though, is that the logic can be defined via liquid markup. This site is edited by a number of contributors, and while they understand the liquid markup well enough to maintain and change its logic as needed, they'd be less confident going in and changing rules within an extension written in ruby. – mdlincoln May 11 '17 at 15:47