【问题标题】:how to include css and js files to php template?如何将 css 和 js 文件包含到 php 模板中?
【发布时间】:2013-11-11 09:23:09
【问题描述】:

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

这是我的 index.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();


?>

这是我的 template.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;
}
}




?>

这是我的 header.php 文件

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

这是我的 footer.php 文件

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

我的 css 文件和 js 文件在 assets 文件夹中,那么如何将它们包含在我的模板中?

【问题讨论】:

    标签: javascript php html css


    【解决方案1】:

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

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

    或者如果你想要非阻塞,把CSS放在header.php和JS放在footer.php

    【讨论】:

    • 然后建议,我认为这会有所帮助
    【解决方案2】:

    对于 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>
    

    【讨论】:

    • 附加信息 在 head 标签之间调用 Css 文件。但是在body末尾调用js文件的原因是为了确保所有的DOM元素都被实例化。
    【解决方案3】:

    为什么要使用“file_get_contents”,可以使用“include_once”来包含你的页脚文件。

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

    希望对你有帮助。

    【讨论】:

    • include_once('path/to/footer.php');对于循环,构建一个包含所有 css 文件的数组,然后在其上循环并构建 css 包含 (),然后像其他标记一样将其注入 {css_head }
    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2023-04-07
    相关资源
    最近更新 更多