テンプレート(View)は使えるようになったので、テンプレートに適用するスタイルシートやJavaScriptを 参照できるようにします。
スタイルシートなどの配置は、kohanaを配置したディレクトリが基準となります。
例えば、public_html/ko3/にkohanaを配置したとして、スタイルシートを次のように配置します。
public_html | |-- /ko3/ | |--/css/ |-- style.css (スタイルシート)
この場合、テンプレート(View)では次のように定義します。
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <?php echo Html::style('css/style.css', array('media'=>'screen, projection'), FALSE),"\n" ?> <title>スタイルシートやJavaScriptを参照するには[kohana 3.x]</title> </head>
Html::style()の部分でlinkタグが作成され次のように出力されます。
<link type="text/css" href="/ko3/css/style.css" rel="stylesheet" media="screen, projection" />
Html::style()の第一引数は、スタイルシートへのパス、第2引数はメディアタイプを指定します。
スタイルシートをモジュール毎に管理したい場合、次のようなディレクトリ構造にします。
public_html | |-- /ko3/ | |--/modules/ | |--/モジュール名/ | |--/css/ |-- style.css (スタイルシート)
この場合、Html::style()の第一引数は次のようになります。
<?php echo Html::style('モジュール名/css/style.css', array('media'=>'screen, projection'), FALSE),"\n" ?>
ここでは、jQueryをGoogle AJAX Libraries APIから直接参照するようにしてみます。
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <?php echo Html::script('https://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js'),"\n" ?> <title>スタイルシートやJavaScriptを参照するには[kohana 3.x]</title> </head>
「テンプレート(View)を使ったhello, world!」でController_Templateを継承しました。 これをさらに拡張してスタイルシートとJavaScriptを組み込みます。
コントローラーを次のように作成します。
<?php defined('SYSPATH') or die('No direct script access.'); class Controller_Website extends Controller_Template { public $template = 'template'; public function before() { parent::before(); if ($this->auto_render) { $this->template->title = ''; } } public function after() { if ($this->auto_render) { $this->template->styles = array( 'css/style.css' => 'screen', 'css/print.css' => 'print', ); $this->template->scripts = array( 'https://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js', ); } parent::after(); } }
テンプレート(View)を次のように作成します。
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <?php foreach ($styles as $file => $type) echo HTML::style($file, array('media' => $type)),"\n" ?> <?php foreach ($scripts as $file) echo HTML::script($file),"\n" ?> <title><?php echo Html::Chars($title) ?></title> </head>
Copyright 1997-2010 BBB All rights reserved.