kohana::模板全攻略
Kohana模板是个很好用的东西,他可以使你的界面统一化。而且便于资源管理。
我建立了几个文件,他们的路径是
其中 demo.php是模板控制器。
代码如下:
<?php defined('SYSPATH') or die('No direct script access.'); class Controller_Demo extends Controller_Template { public $template = 'demo/template'; /** * before()方法在你的控制器动作执行前被调用 * 在我们的模板控制器中,我们覆盖了这个方法,那么我们就能设置默认值。 * 那么这些变量需要改变的时候我们的控制器也能使用它们 */ public function before() { parent::before(); if ($this->auto_render) { // Initialize empty values $this->template->title = 'gobang'; $this->template->content = '赞无内容'; $this->template->styles = array(); $this->template->scripts = array(); } } /** * after()方法在控制器动作执行后调用 * 在我们的模板控制器中,我们覆写了这个方法,那么我们就能 * 在模板显示之前做最后的一些改变 */ public function after() { if ($this->auto_render) { $styles = array( 'media/css/screen.css' => 'screen, projection', 'media/css/print.css' => 'print', 'media/css/style.css' => 'screen', ); $scripts = array( 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', 'media/jquery/jquery-1.9.1.js', ); $this->template->styles = array_merge( $this->template->styles, $styles ); $this->template->scripts = array_merge( $this->template->scripts, $scripts ); } parent::after(); } }
template.php
<head profile="http://gmpg.org/xfn/11"> <title><?php echo $title ?></title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <?php foreach ($styles as $file => $type) echo HTML::style($file, array('media' => $type)), "\n" ?> <?php foreach ($scripts as $file) echo HTML::script($file), "\n" ?> </head> <body> <?php echo $content ?> </body> </html>
Media.php控制器是为了实现HTML:css的路径
<?php /** * 定位media路径 * @author xyt */ class Controller_Media extends Controller { public function action_serve() { $file = $this->request->param ( "file" ); $param=explode(".",$file); $file=$param[0]; $theme = $this->request->param ( 'theme' ); $url=$this->finddir($file,$theme); $this->response->body(file_get_contents($url)); } public function finddir($file,$theme){ $arr = explode ( '/', $file ); $mys =array_pop ( $arr ); $arr = implode ( '/', $arr ); if(isset($arr) && $arr=="") { $dir = "media/" . $theme ; } else{ $dir = "media/" . $theme . "/" . $arr; } switch ($theme) { case "css": return Kohana::find_file ( $dir, $mys,"css" ); break; case "js": return Kohana::find_file ( $dir, $mys,"js" ); break; default: return Kohana::find_file ( $dir, $mys); break; } } }