LoginSignup
49
44

More than 5 years have passed since last update.

ファイル新規作成時にテンプレートの値を挿入する。

Last updated at Posted at 2014-06-04

概要

vimからファイルを新規作成する際に、拡張子によってその新規作成されるファイルの中身をテンプレートから自動で読みこむようにする。
サンプルとしてHTMLファイル。

テンプレートファイルの準備

$HOME/.vim/template/html.txtを作成する。
ディレクトリがなければ作成する。

$HOME/.vim/template/html.txt
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex,nofollow" />
<meta charset="UTF-8">
<title>This is Template</title>

<!--** jQuery **-->
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>

<!--** Bootstrap **-->
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

<!--** other CSS **-->
<!--<link rel="stylesheet" type="text/css" href="example.css">-->
<style type="text/css">
</style>

<!--** other JavaScript **-->
<!--<script type="text/javascript" src="example.js"></script>-->
<script type="text/javascript">
$(document).ready(function(){
    // Initial Code
});
</script>
</head>
<body>
<p>Hello World!</p>
</body>
</html>

ファイル作成時に拡張子がhtmlならテンプレートを読みこむようにする。

.vimrcに下記の1行を追記する。

$HOME/.vimrc
autocmd BufNewFile *.html 0r $HOME/.vim/template/html.txt

これでvimからhtmlファイルを作成すると、今回用意したテンプレートの内容が自動的に挿入されるようになる。

49
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
44