我想在我所有的网站页面中都有动态的 header.php,并且有很多 CSS 文件需要加载。有没有办法为每个页面加载不同的 CSS 文件?例如:
<?php if($title == "title") { ?>
<link href="mycss.css" >
<script src="test.js"></script>
<?php } ?>
最佳答案
您可以创建一个函数(或类)来将您的 header 和提要参数作为设置回显。这样的事情可能会起作用:
function.get_header.php
// This function will render the header
function get_header($settings = false)
{
ob_start();
include("header.php");
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function.get_page_css.php
// This function will act like a pseudo database return
// and will return a series of css links based on input
function get_page_css($var = false)
{
$css['title'][] = "/css/style1.css";
$css['other'][] = "/css/style2.css";
$css['title'][] = "/css/style3.css";
if(!empty($css[$var]))
return $css[$var];
}
header.php
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title><?php echo (!empty($settings['title']))? $settings['title'] : "Untitled Page"; ?></title>
<head>
<?php if(!empty($settings['css']) && is_array($settings['css'])) {
foreach($settings['css'] as $link) {
?>
<link type="text/css" rel="stylesheet" href="<?php echo $link; ?>" />
<?php }
}
?>
</head>
index.php
<?php
// Include the header function
include("function.get_header.php");
// Include the css return function
include("function.get_page_css.php");
// Write the header to browser using the get_page_css() function
echo get_header(array("title"=>"This Great Page!","css"=>get_page_css('title')));
?>
<body>...etc.
关于php - 如何在php中的特定页面加载CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33361274/