Philip Durbin
Philip Durbin

Reputation: 4072

How can I make Jekyll use a layout without specifying it?

In order to keep some of my Jekyll sites simple, I'm always using the same layout. That is to say, I'm always writing something like. . .

---
layout: default
title: Here's my Title
---

. . . as the YAML Front Matter at the top of my pages.

What I'd rather write, however is only. . .

---
title: Here's my Title
---

. . . and have Jekyll assume that it should use a certain layout, as if I had explicitly written "layout: default" (or whatever), as above.

I don't see a way to specify this behavior in _config.yml. Maybe I could write a Jekyll plugin that would allow this. . . any ideas?

Upvotes: 24

Views: 5016

Answers (4)

Martin
Martin

Reputation: 10878

This can be done using Frontmatter defaults:

defaults:
  -
    scope:
      path: "" # empty string for all files
    values:
      layout: "default"

This setting is available since Jekyll Version 2.0.0.

Upvotes: 27

Hakan Ensari
Hakan Ensari

Reputation: 1979

Shorter and with no monkey-patching:

# _plugins/implicit_layout.rb
module ImplicitLayout
  def read_yaml(*args)
    super
    self.data['layout'] ||= 'post'
  end
end

Jekyll::Post.send(:include, ImplicitLayout)

Caveat: GH Pages won't run your plugins.

Upvotes: 5

Brett Hardin
Brett Hardin

Reputation: 4052

By default, you can't do this. Jekyll needs the YAML to specify layout so it knows where to drop it in at.

Upvotes: 0

Philip Durbin
Philip Durbin

Reputation: 4072

Here's a Jekyll plugin you can drop in as _plugins/implicit-layout.rb, for example:

# By specifying an implicit layout here, you do not need to
# write, for example "layout: default" at the top of each of
# your posts and pages (i.e. in the "YAML Front Matter")
#
# Please note that you should only use this plugin if you
# plan to use the same layout for all your posts and pages.
# To use the plugin, just drop this file in _plugins, calling it
# _plugins/implicit-layout.rb, for example
IMPLICIT_LAYOUT = 'default'

module Jekyll
  module Convertible

    def read_yaml(base, name)
      self.content = File.read(File.join(base, name))

      if self.content =~ /^(---\s*\n.*?\n?)^(---\s*$\n?)/m
        self.content = $POSTMATCH

        begin
          self.data = YAML.load($1)
          self.data["layout"] = IMPLICIT_LAYOUT
        rescue => e
          puts "YAML Exception reading #{name}: #{e.message}"
        end
      end

      self.data ||= {}
    end

  end
end

From hanging out on #jekyll on freenode, I'm given to understand this is a monkey patch.

As Alan W. Smith commented, being able to put "layout: default" in _config.yml would be a nice improvement to this plugin.

Ideally (from my perspective), this functionality could be incorporated in Jekyll itself so a plugin wouldn't be necessary.

Upvotes: 0

Related Questions