Slim Framework + Twig + Assetic 的整合


最近在使用上的筆記.直接上代碼.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
// 載入相應的物件
use Slim\Slim;
use Slim\Extras\Views;
use Assetic\FilterManager;
use Assetic\AssetWriter;
use Assetic\Filter\CSSMinFilter;
use Assetic\Factory\AssetFactory;
use Assetic\Factory\LazyAssetManager;
use Assetic\Factory\Worker\CacheBustingWorker;
use Assetic\Extension\Twig\AsseticExtension;
use Assetic\Extension\Twig\TwigFormulaLoader;
use Assetic\Extension\Twig\TwigResource;

// 設置 Filter 的類型
$filter_manger = new FilterManager();
$filter_manger->set('cssmin', new CSSMinFilter());

// 設置 Asset 目錄,打開 Debug,指定 Filter,輸出模式
$asset_factory = new AssetFactory(PUBLIC_ROOT);
$asset_factory->setDebug(false);
$asset_factory->setFilterManager($filter_manger);
$asset_factory->addWorker(new CacheBustingWorker(CacheBustingWorker::STRATEGY_CONTENT));

// 設定 Slim 的 Twig View 的模板和緩存位置等
Views\Twig::$twigTemplateDirs = array(VIEWS_ROOT);
Views\Twig::$twigOptions = array(
'charset' => 'utf-8',
'cache' => realpath(CACHE_ROOT.'/views'),
'auto_reload' => true,
'strict_variables' => false,
'autoescape' => true
);

// 加入 Twig 的 extensions 支援 urlFor 和 Asset 標籤
Views\Twig::$twigExtensions = array(
'Twig_Extensions_Slim',
new AsseticExtension($asset_factory)
);

// 初始化 Twig View Engine
$view_engine = new Views\Twig();

// 設置 LazyAssetManager,傳入目前的 AssetFoctory 物件和 Twig 的資料
$asset_manger = new LazyAssetManager($asset_factory);
$asset_manger->setLoader('twig', new TwigFormulaLoader($view_engine->getEnvironment()));

// 將所有模版都讀入到資料管理器中,等待後面寫入到檔案
$templates = array();
$directories = array(VIEWS_ROOT);
while (sizeof($directories)) {
$directory = array_pop($directories);

foreach(glob($directory."/*") as $file_path) {
if (is_dir($file_path) === true) {
array_push($directories, $file_path);
}elseif (is_file($file_path) === true && preg_match("/\.(html)$/", $file_path) == true) {
$templates[] = str_replace(VIEWS_ROOT, '', $file_path);
}
}
}

foreach ($templates as $template) {
$resource = new TwigResource(new \Twig_Loader_Filesystem(VIEWS_ROOT), $template);
$asset_manger->addResource($resource, 'twig');
}

// 將目前已解釋的 Asset 標籤都寫入到指定的檔案
$asset_writer = new AssetWriter(WWW_ROOT);
$asset_writer->writeManagerAssets($asset_manger);

// 在模版中加入相應的 Asset 標籤即可

{% stylesheets output='public/asset/default.css'
'css/bootstrap.min.css'
'css/default.css'
'css/bootstrap-responsive.min.css' %}
<link href="{{ asset_url }}" type="text/css" rel="stylesheet" />
{% endstylesheets %}

{% stylesheets output='public/asset/default.js'
'js/jquery.min.js'
'js/bootstrap.min.js'
'js/default.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endstylesheets %}