Module: Jekyll::Filters::YamlToScss

Defined in:
lib/jekyll/filters/yaml_to_scss.rb

Overview

YAML to SCSS

Instance Method Summary collapse

Instance Method Details

#yaml_to_scss(yaml, schema = yaml) ⇒ String

Converts a YAML object into SCSS. Only supports one level values.

Optionally give it an schema to filter out keys.

You can add an array of keys to remove from the schema on _config.yml, so if you’re using a post to get an schema from, some values don’t end up on the SASS/SCSS file.

Parameters:

  • :yaml (Hash, Jekyll::Drops::DocumentDrop)
  • :schema (Hash)

Returns:

  • (String)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/jekyll/filters/yaml_to_scss.rb', line 19

def yaml_to_scss(yaml, schema = yaml)
  yaml = yaml.to_h if yaml.is_a? Jekyll::Drops::DocumentDrop

  unless yaml.is_a? Hash
    raise Liquid::ArgumentError, "#{yaml.inspect} needs to be a Hash" if @context.strict_filters

    return yaml
  end

  site = @context.registers[:site]
  keys = schema.keys
  reject_keys = site.config.dig('liquid', 'yaml_to_scss', 'reject_keys')

  if reject_keys.is_a?(Array) && !reject_keys.empty?
    keys = keys - reject_keys
  end

  yaml.slice(*keys).map do |key, value|
    next if value.nil?

    escape = schema[key].is_a?(Hash) && %w[image file].include?(schema.dig(key, 'type'))
    key = key_to_scss key

    case value
    when Array
      values = value.compact.map(&:to_s).reject(&:empty?).map do |v|
        escape ? v.dump : v
      end

      next if values.empty?

      "$#{key}: (#{values.join(',')},);"
    when Hash
      values =
        value.map do |k, v|
          next if v.nil?
          next if v.to_s.empty?

          v = v.dump if escape

          "\"#{key_to_scss k}\": #{v}"
        end.compact

      next if values.empty?

      "$#{key}: (#{values.join(',')},);"
    else
      next if value.to_s.empty?
      value = value.dump if escape

      "$#{key}: #{value};"
    end
  end.join("\n")
end