powered by nequal

rhaco1-doc :: 099-tips/02-one-file-script.txt

http://wikihub.org/wiki/rhaco1-doc/099-tips/02-one-file-script

Table of contents:

collapse all expand all

Updates:

テンプレートを内蔵した1ファイルスクリプト

一般的なテンプレートエンジンでは,スクリプトとテンプレートを分けます.

というか,そもそもそれが目的なんですけどね.

ところが,一画面しかないちょっとしたスクリプトでテンプレートエンジンを使おうと思うと大変ですよね.素の PHP で書いても良いのですが,メンテが面倒です.

そんな時,rhaco では,次のような感じで実装できます.

<?php
include_once dirname(__FILE__).'/__init__.php';
Rhaco::import("generic.Flow");
$flow = new Flow();
$cnt = (int)$flow->getVariable("cnt",1);
if($flow->isPost()){
	$cnt++;
}
$flow->setVariable("name",$flow->getVariable("name","ななし"));
$flow->setVariable("cnt",$cnt);
$flow->parser(__FILE__)->write();
Rhaco::end();
?>
<rt:template>
<html>
<head>
<title>1ファイルスクリプト</title>
</head>
<body>
{$f.text2html($name)}さんこんにちは!{$cnt}回目だね!
<form method="post" rt:reference="true">
	名前:<input type="text" name="name"/>
	<input type="hidden" name="cnt"/>
	<input type="submit" value="送信"/>
</form>
</body>
</html>
</rt:template>

はい,簡単ですね!

こんな感じで,ロジックとテンプレートの分離も1ファイルで実現できます.

ここでは,"<rt:template/>" タグが肝です.このタグがある場合には,その中身だけがテンプレートとして処理されます.

ちょっとした入力画面付きスクリプトを書くときなんかには重宝しますね.

テンプレートを内蔵した1ファイルライブラリ

お前何言ってるんだ?って感じですね.私もそう思います.この節は,ほんと参考程度です.

例えば,arbo.generic.ExSetupViews は,リソース(テンプレート)付きのパッケージライブラリです.これは,コードとテンプレートを分離していますが,テンプレートが1つしかない場合には,やろうと思えば1ファイルにまとめることができます.

<?php
Rhaco::import("network.http.Header");
Rhaco::import("setup.util.SetupView");
Rhaco::import("setup.model.ProjectModel");
 
/**
 * project.xml で指定した設定項目を変更するView
 *
 * @author Naoki
 * @license New BSD License
 * @copyright Copyright 2009- rhaco project. All rights reserved.
 */
class ExSetupViews extends SetupView
{
        /**
         * setup
         *
         * @param mixed
         * @return HtmlParser
         */
        function setup()
        {
		//略
                return $this->parser(FileUtil::exist(Rhaco::templatepath("setup/setup.html")) ?
                                                                Rhaco::templatepath("setup/setup.html") :
                                                                __FILE__
                                                        );
        }
}
/*
<rt:template>
<html>
<head>
 
</head>
<body>
 
</body>
</html>
</rt:template>
*/
?>

はい,できました.