LoginSignup
2

More than 5 years have passed since last update.

静的サイトジェネレータ S.S.J (Seiteki Saito Jenereta)

Posted at

簡易静的サイトジェネレーター S.S.J

ヘッダ・サイドバー・フッタなどのセクションを共通化する仕組みです。

特別なテンプレートは不要で、共通セクションの元となるHTML(デフォルトではindex.html)から、セクション部分を他のHTMLにコピーします。

ソースコード

ssj.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Seiteki Saito Jenereta</title>
</head>
<body>
<?php
// 反映元
$src = 'index.html';

// 反映先
$dists = ['company.html', 'contact.html'];

// セクション
$sections = ['header', 'sidebar', 'footer'];

$parts = [];
$html = file_get_contents($src);
foreach ($sections as $section) {
    preg_match('|<!-- <' . $section . '> -->(.*?)<!-- /<' . $section . '> -->|s', $html, $ms);
    $parts[$section] = $ms[1];
}
preg_match_all('|<!-- <slot(\d+?)> -->.*?<!-- /<slot\d+?> -->|s', $html, $mss, PREG_SET_ORDER);
$slots = [];
foreach ($mss as $ms) $slots[$ms[1]] = null;
foreach ($dists as $dist) {
    echo "$dist:<br>";
    $html = file_get_contents($dist);
    foreach ($slots as $no => $slot) {
        if (preg_match('|<!-- <slot' . $no . '> -->(.*?)<!-- /<slot' . $no . '> -->|s', $html, $ms)) {
            $slots[$no] = $ms[1];
        } else {
            $slots[$no] = null;
        }
    }
    foreach ($parts as $section => $part) {
        $html = preg_replace('|(<!-- <' . $section . '> -->).*?(<!-- /<' . $section . '> -->)|s', '${1}' . $part . '${2}', $html);
        echo " section: $section OK<br>";
    }
    foreach ($slots as $no => $slot) {
        if ($slot) {
            $html = preg_replace('|(<!-- <slot' . $no . '> -->).*?(<!-- /<slot' . $no . '> -->)|s', '${1}' . $slot . '${2}', $html);
            echo " slot$no: $slot OK<br>";
        }
    }
    file_put_contents($dist, $html);
    echo '<br>';
}
?>
</body>
</html>

実行方法

必要なファイルはssj.phpのみです。
ブラウザで開くと実行されます。

その他のHTMLとCSSファイルは動作確認用のサンプルです。

カスタマイズ

$src

共通セクションのコピー元。

$dists

共通セクションのコピー先。

$sections

共通セクション名。

セクションについて

コメントで<!-- <セクション名> --><!-- /<セクション名> -->に囲まれた部分が共通セクションとなります。

セクション名はデフォルトではheader, sidebar, footerを定義していますが、自由に名付けることもできます。

スロットについて

共通セクションの内部にスロットを定義すると、その部分だけは上書きされなくなります。

コメントで<!-- <slotスロット番号> --><!-- /<slotスロット番号> -->に囲まれた部分がスロットとなります。
スロット番号は1から順番に付けてください。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2