create new post for jekyll

Dec 23, 2014 • CoderSimple 原文传送阵

如何在 jekyll 下面通过命令新建一篇文章?通过查找并没有发现相关的命令,玩过 octopress 的人都知道,octopress 通过 rake new_post [title] 就可以新建一篇文章,而 octopress 也是基于 jekyll 的,那么 octopress 里面是怎么做到的呢?通过查找相关资料了解到,当我们在 octopress 工程目录下执行rake new_post [title] 的时候是在执行该目录下 Rakefile 中定义的方法而已,因此我就把 octopress 的工程克隆下来,找到其中的 Rakefile,拷贝到自己的 jekyll 工程目录下,并做简单的修改。

需要库 stringex,如何安装引用库请看 bundler for jekyll

修改后文件如下:

require "stringex"

posts_dir       = "_posts"
new_post_ext    = "md"

task :new_post, :title do |t, args|
  if args.title
    title = args.title
  else
    title = get_stdin("Enter a title for your post: ")
  end

  mkdir_p "#{posts_dir}"
  filename = "#{posts_dir}/#{Time.now.strftime('%Y-%m-%d')}-#{title.to_url}.#{new_post_ext}"
  if File.exist?(filename)
    abort("rake aborted!") if ask("#{filename} already exists. Do you want to overwrite?", ['y', 'n']) == 'n'
  end
  puts "Creating new post: #{filename}"
  open(filename, 'w') do |post|
    post.puts "---"
    post.puts "layout: post"
    post.puts "title: \"#{title.gsub(/&/,'&')}\""
    post.puts "date: #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}"
    post.puts "published: true"
    post.puts "categories: "
    post.puts "---"
  end
end


def get_stdin(message)
  print message
  STDIN.gets.chomp
end

def ask(message, valid_options)
  if valid_options
    answer = get_stdin("#{message} #{valid_options.to_s.gsub(/"/, '').gsub(/, /,'/')} ") while !valid_options.include?(answer)
  else
    answer = get_stdin(message)
  end
  answer
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值