sharedhat

今回はテンプレートの作成について解説します。
テンプレートを作成すると、いつもよく利用しているファイルなどをテンプレートから作成することができます。

また、テンプレート内にプレースホルダーを指定すると、ファイル作成時に特定の値を埋め込んで、新しいファイルを作成してくれます。

今回のサンプルバンドルを作成したので、参考にしてください。
http://dl.dropbox.com/u/603849/example.ruble-template.zip

テンプレート定義

テンプレートファイルの作成

templatesディレクトリの直下にテンプレートファイルを作成します。
テンプレートファイル名やテンプレートファイルは何でもかまわないです。

ここではHTML5のテンプレートファイルを作成します。
templatesディレクトリにテンプレートファイルを作成します。

templates/html5_default_template.html

テンプレートの定義

次にテンプレートの定義ファイルを作成します。
テンプレート定義ファイルはtemplatesディレクトリの直下にtemplates.rbという名前で作成します。

スニペットと同様に最初にrubleモジュールを読み込みます。

require 'ruble'

そして肝心のテンプレート定義を記述します。
ここではテンプレート中のプレースフォルダーを環境変数で置換して結果をテンプレートの内容として返しています。
プレースフォルダーは${変数名}という形式でテンプレート内に記述します。

環境変数は下記のページに掲載されています。

環境変数一覧:
http://wiki.appcelerator.org/display/tis/Ruble+environment+variables

require 'ruble'

template [template_name] do |tmpl|

	template_file = "#{ENV['TM_BUNDLE_SUPPORT']}/../templates/[template_file_name]"

	tmpl.filetype = [file_type]
	tmpl.invoke do |context|
		raw_contents = IO.read(template_file)
		raw_contents.gsub(/\$\{([^}]*)\}/) { |match| ENV[match[2..-2]] }
	end

end

各項目は下記の通りになります。

template_name テンプレート名です。
この名称でメニューに表示されます。
template_file_name テンプレートのファイル名です。
file_type テンプレートのファイルタイプです。
*.htmlと指定した場合はhtmlファイルの作成時にテンプレートの選択肢に表示されます。

最終的なテンプレート定義は下記の通りです。

require 'ruble'

#HTML5 Template file
template 'HTML5 Template file' do |tmpl|
	tmpl.filetype = '*.html'
	tmpl.invoke do |context|
		template_file = "#{ENV['TM_BUNDLE_SUPPORT']}/../templates/html5_default_template.html"
		raw_contents = IO.read(template_file)
		raw_contents.gsub(/\$\{([^}]*)\}/) { |match| ENV[match[2..-2]] }
	end
end

テンプレートの動作確認

バンドルのディレクトリからcache.yamlを削除して、Bundlesビューより再読み込みしてみます。
そして、ファイルメニューのNew From Templateからテンプレートを選択します。

無事テンプレートからファイルが作成され、プレースホルダーが置き換わっていたら完了です。

Trackback:

It is a comment that has been gotten before.

トラックバックを下記のURLに送ってください。
http://sharedhat.com/blog/1744/trackback/

Reply:

Please give the comment to this article.





個人的なフォトログサイト

Wordpressのフォトログテーマ

Concrete5のアドオンパッケージ

this site is licensed under a Creative Commons License But, a part of contents is excluded.
Powered by WordPress