如何将 CSS 和 JS 文件包含在 PHP 模板中


how to include css and js files to php template?

我已经为PHP网站构建了我的简单模板。问题是我不知道包含我的 CSS 和 JavaScript 文件的好方法。

这是我的索引.php文件

<?php
include'core/template.php';
$temp=new Template();
$settings=array("title","page_title","welcome_word");
$values=array("RIS - Home","Results Information System","Welcome to result 
               Information      system");
$temp->header($settings,$values);
$temp->footer();

?>

这是我的模板.php文件

<?php
class Template {
public function header($setting,$values){
    $file=file_get_contents("http://localhost/RIS/src/header.php");
    $count=0;
    foreach ($setting as $setting) {
        $file=str_replace('{'.$setting.'}',$values[$count],$file);
        $count++;
    }
    echo $file;
}
public function footer(){
    $file=file_get_contents("http://localhost/RIS/src/footer.php");
    echo $file;
}
}


?>

这是我的标题.php文件

<!DOCTYPE html>
<html>
<head>
    <title>{title}</title>
    </head>
<body>
    <header>
        <h1>{page_title}</h1>
            {welcome_word}
    </header>
    My contents goes here...

这是我的页脚.php文件

<footer>
Copyright &copy; RIS 2013.
</footer>
</body>
</html>

我的 CSS 文件和 JS 文件位于资产文件夹中,那么如何将它们包含在我的模板中?

我会使用输出缓冲区和包含而不是file_get_contents,include'core/template.php';这里缺少空格。

在你的情况下,为什么不把CSS和JS放到header.php呢?

或者,如果您想要非阻塞,请将 CSS 放在页眉中.php将 JS 放在页脚中.php

对于 CSS 文件:

<!DOCTYPE html>
<html>
<head>
    <title>{title}</title>
    <link rel="stylesheet" href="path/to/assets/yourcss.css" type="text/css">
</head>
<body>
    <header>
        <h1>{page_title}</h1>
            {welcome_word}
    </header>
    My contents goes here...

对于 JavaScript:

<footer>
Copyright &copy; RIS 2013.
</footer>
<script src="path/to/assets/yourjs.js"></script>
</body>
</html>

为什么使用"file_get_contents",可以使用"include_once"来包含页脚文件。

对于您的模板,为 css 放置一个标记,并在 php 中构建您的 css 数组,然后将其注入到您的标记中。

希望对您有所帮助。