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

问题描述 投票:2回答:1

我有一个关于使用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> 
php html
1个回答
1
投票

以下是我用于为任何嵌套目录自动加载我的PHP类的内容,这也适用于您的前端资源:

<?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">

文档:

© www.soinside.com 2019 - 2024. All rights reserved.