如何让Jekyll使用布局而不指定它?

时间:2011-12-13 14:06:21

标签: ruby jekyll jekyll-extensions

为了让我的一些Jekyll网站变得简单,我总是使用相同的布局。也就是说,我总是在写类似的东西。 。

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

。 。 。作为我页面顶部的YAML Front Matter

我宁愿写的只是。 。

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

。 。 。让Jekyll假设它应该使用某种布局,就好像我已经明确地写了“layout: default”(或其他),如上所述。

我没有看到在_config.yml中指定此行为的方法。也许我可以写一个允许这个的Jekyll plugin。 。 。任何想法?

4 个答案:

答案 0 :(得分:27)

可以使用Frontmatter defaults

完成此操作
defaults:
  -
    scope:
      path: "" # empty string for all files
    values:
      layout: "default"

此设置自Jekyll Version 2.0.0以来可用。

答案 1 :(得分:5)

更短,没有猴子补丁:

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

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

警告:GH Pages不会运行您的插件。

答案 2 :(得分:0)

这是一个Jekyll插件,您可以将其作为_plugins/implicit-layout.rb插入,例如:

# 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

在freenode的#jekyll上闲逛时,我明白这是一个猴子补丁。

正如Alan W. Smith评论的那样,能够在layout: default中添加“_config.yml”对这个插件来说是一个很好的改进。

理想情况下(从我的角度来看),此功能可以合并到Jekyll本身,因此不需要插件。

答案 3 :(得分:0)

默认情况下,您无法执行此操作。 Jekyll需要YAML指定布局,因此它知道放在哪里。

相关问题