动态包含用于保存js和CSS资源的header.php文件

时间:2018-08-30 09:31:45

标签: php html

我对使用PHP包含头文件有疑问。

上面的代码是我包含在所有HTML / PHP视图文件中的标头。我想将其保存在名为命名约定header.php的文件中。
我对资源的加载感到怀疑。

如果包含另一个css和js主文件夹的文件夹中包含标头,那么如何加载所需的样式表和js文件?

我想避免基本资源的重复,并避免由于资源文件的位置而导致控制台错误。

<!DOCTYPE html>
<html lang="it">
<head>
<!-- basic meta tag -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- add facebook og tag here -->
<meta property="og:url" content="" />
<meta property="og:type" content="article" />
<meta property="og:title" content="" />
<meta property="og:description" content="" />
<meta property="og:image" content="" />
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://masserianobile.it; font-src 'self' https://fonts.gstatic.com/; img-src 'self'; style-src 'self' https://fonts.googleapis.com/;">  -->

<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/fontawesome-all.min.css" type="text/css">
<link rel="stylesheet" href="css/app.min.css" type="text/css">

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src=""></script>

</head> 

1 个答案:

答案 0 :(得分:1)

这是我用来为任何嵌套目录自动加载我的 PHP类的方法,这也可以用于您的 Front-End 资源:

<?php

/* the root directory of your project
   can be useful when working on local env
   must not end with a slash, leave it empty if not needed */
const ROOT_PATH = '/projects/some_stuff';

// Get parts of the URL without the root path
$rel_path = explode('/', str_replace(ROOT_PATH, '', $_SERVER['SCRIPT_NAME']));

// Remove empty items from the parts
$rel_path = array_filter($rel_path);

// If the last part is a php file, remove it, we don't need it
if (strpos(end($rel_path), '.php') !== false) { array_pop($rel_path); }

// Build the "../" prefix
$prefix = implode('/', array_fill(0, count($rel_path), '..'));
$prefix = empty($prefix) ? '' : $prefix . '/';

?>

<!-- just output the prefix before the resource URL -->
<link rel="stylesheet" href="<?php echo $prefix; ?>css/bootstrap.min.css" type="text/css">

文档: